题意:把整数转换成十六进制数
思路:把数字和15于8次,每次把于出来的十六进制字符加入结果,并把temp右移4位,如果中间遇到temp==0break,最后把字符串翻转并转换成字符串
思想:位运算
复杂度:时间O(n),空间O(1)
class Solution {
public String toHex(int num) {
String[] m = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"};
int temp = num;
StringBuilder sb = new StringBuilder();
while(sb.length() < 8) {
int cur = temp & 15;
sb.append(m[cur]);
temp = temp >> 4;
if(temp == 0)
break;
}
return sb.reverse().toString();
}
}
网友评论