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';
}
}