convert-a-number-to-hexadecimal
https://leetcode.com/problems/convert-a-number-to-hexadecimal/ // https://discuss.leetcode.com/topic/60365/simple-java-solution-with-comment/4 public class Solution { public String toHex(int num) { char []cmap = {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'}; StringBuilder sb = new StringBuilder(); do { sb.append(cmap[num & 15]); num >>>= 4; } while (num != 0); return sb.reverse().toString(); } }
注意,以上代码里面的 >>> 是无符号位移。也就是不管正数负数,左边空出来的位都是补0.
<< : 左移运算符,num << 1,相当于num乘以2
>> : 右移运算符,num >> 1,相当于num除以2
>>> : 无符号右移,忽略符号位,空位都以0补齐
而C++里面的 >> 根据编译器不同有所区别。一般而言,是带符号的,如果负数,会补1.