Convert a Number to Hexadecimal
Given an integer num, return a string representing its hexadecimal representation. For negative integers, two’s complement method is used.
All the letters in the answer string should be lowercase characters, and there should not be any leading zeros in the answer except for the zero itself.
Note: You are not allowed to use any built-in library method to directly solve this problem.
Example 1:
Input: num = 26
Output: "1a"
Example 2:
Input: num = -1
Output: "ffffffff"
Constraints:
-231 <= num <= 231 - 1
思路一:先把整数当成二进制,每4个 bit 位就是一个16进制字符,循环取整数低位的4个 bit 位,可以计算得到16进制。看了一下题解,补码的操作是不用的
public String toHex(int num) {
if (num == 0) {
return "0";
}
//不用处理
// if (num < 0) {
// num = -num - 1;
// num ^= 0xffffffff;
// }
String[] values = {"a", "b", "c", "d", "e", "f"};
StringBuilder sb = new StringBuilder();
while (num != 0) {
int x = num & 0b1111;
num >>>= 4;
if (x >= 10) {
sb.insert(0, values[x - 10]);
} else {
sb.insert(0, x);
}
}
return sb.toString();
}
标签:10,return,String,405,num,easy,Input,sb,leetcode
From: https://www.cnblogs.com/iyiluo/p/17064613.html