1 检查回文字符串
A string is a palindrome if it reads the same forward and backward. The words “mom,” “dad,”
and “noon,” for instance, are all palindromes.
import java.util.Scanner;
public class CheckPalin
{
public static void main(String [] args)
{
Scanner input=new Scanner(System.in);
String s=input.nextLine();
int j=s.length()-1;
int i=0;
if(ifPar(s))
System.out.println("the string "+s+" is a palindromes");
else
System.out.println("the string "+s+" is not a palindromes");
}
public static boolean ifPar(String s)
{
int i=0;
int j=s.length()-1;
while(i<j)
{
if(s.charAt(i)!=s.charAt(j)) return false;
j--;
i++;
}
return true;
}
}
这里注意String 中一些常见的一些方法,例如charAt(index) 返回index位置的字符,他相对是是indexof(char c)返回char c在字符串中的index
2 十六进制转为十进制
一个十六进制 hnhn-1……h1h0转为十进制是
Hn*16n+hn-1*16n-1+…….h1*16+h0
可以化简为
(…((hn*16+hn-1)*16+hn-2)*16+…..+h1)*16+h0 这样可以用一个变量来存放结果,从index=0开始遍历,将读到的字符化为int(用n存放), 然后result=result*16+n
<span style="font-family: Arial, Helvetica, sans-serif;">import java.util.Scanner;</span>
public class HexToDec
{
public static void main(String [] args)
{
Scanner input = new Scanner(System.in);
String hexS=input.nextLine();
System.out.println("Hex:"+hexS+" to Dec: "+hexToDec(hexS));
}
public static int hexToDec(String s)
{
int result=0;
for(int i=0;i<s.length();i++)
{
int n=hexCharToDec(s.charAt(i));
result=result*16+n;
}
return result;
}
public static int hexCharToDec(char a)
{
if(a>='A' && a<='F') return a-'A'+10;
else return a-'0';
}
}