Generate the hexadecimal representation for a given non-negative integer number as a string. The hex representation should start with "0x".
There should not be extra zeros on the left side.
Examples
- 0's hex representation is "0x0"
- 255's hex representation is "0xFF"
Solution: 注意0
public String hex(int number) {
if (number == 0) {
return "0x0";
}
StringBuilder sb = new StringBuilder();
while (number > 0) {
int remain = number % 16;
if (remain > 9) {
//要有强制转换
char c = (char)(remain - 10 + 'A');
sb.append(c);
} else {
sb.append(remain);
}
number /= 16;
}
sb.append("x0");
int i = 0, j = sb.length() - 1;
//或者直接sb.reverse()
while (i < j) {
char temp = sb.charAt(i);
sb.setCharAt(i, sb.charAt(j));
sb.setCharAt(j, temp);
//记得i++, j-- !!
i++;
j--;
}
return sb.toString();
}