題意:把整數(shù)轉(zhuǎn)換成十六進(jìn)制數(shù)
思路:把數(shù)字和15于8次,每次把于出來(lái)的十六進(jìn)制字符加入結(jié)果,并把temp右移4位,如果中間遇到temp==0break,最后把字符串翻轉(zhuǎn)并轉(zhuǎn)換成字符串
思想:位運(yùn)算
復(fù)雜度:時(shí)間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();
}
}