进制转换及回文判断
程序员文章站
2024-03-19 22:15:10
...
1、进制转换
十进制转二进制、八进制、十六进制
思想:辗转相除法
// 十进制转十六进制
private static void decToHex(int num) {
String hex = "";
int shang = num;
int yu;
while(shang != 0) {
yu = shang % 16;
shang = shang / 16;
char result;
if(yu > 9)
result = (char) ('A' + (yu - 10));
else
result = (char) ('0' + (yu - 0));
hex = result + hex;
}
System.out.println(num + "的16进制: " + hex);
}
// 十进制转二进制
private static void decToBinary(int num) {
String binary = "";
int yu;
int shang = num;
while(shang != 0) {
yu = shang % 2;
shang = shang / 2;
binary = yu + binary;
}
System.out.println(num + " 的二进制: " + binary);
}
// 十进制转八进制
private static void decToOct(int num) {
String oct = "";
int yu;
int shang = num;
while(shang != 0) {
yu = shang % 8;
shang = shang / 8;
oct = yu + oct;
}
System.out.println(num + " 的八进制: " + oct);
}
2、回文判断
注意点:
1、字符串长度可分为 奇数 和 偶数 两种
2、边界值分析
// 使用普通方式
private static void isPlalindrome() {
Scanner cin = new Scanner(System.in);
System.out.println("输入目标字符串: ");
String str = cin.nextLine();
boolean isPalindrome = false;
int begin = 0;
int end = str.length() - 1;
while (begin < end && str.charAt(begin) == str.charAt(end)) {
begin ++;
end --;
}
if (begin >= end) // 奇偶数长度的字符串统一处理
isPalindrome = true;
System.out.println(str + (isPalindrome ? "" : "不") + "是一个回文字符串.");
}