[位运算]405. Convert a Number to Hexadecimal

十进制转十六进制。
除了0,首位都不为0;字母全部小写;num可能为负数。
题目:405. Convert a Number to Hexadecimal

另外二进制位运算加法 题目:371. Sum of Two Integers

Given an integer, write an algorithm to convert it to hexadecimal. For negative integer, two’s complement method is used.
Note:
All letters in hexadecimal (a-f) must be in lowercase.
The hexadecimal string must not contain extra leading 0s. If the number is zero, it is represented by a single zero character '0'; otherwise, the first character in the hexadecimal string will not be the zero character.
The given number is guaranteed to fit within the range of a 32-bit signed integer.
You must not use any method provided by the library which converts/formats the number to hex directly.

Example 1:

Input:26 Output:"1a"

Example 2:

Input:-1Output:"ffffffff"

二进制,计算每四位得到一个十六进制的位。

需要注意,因为可能为负数,所以用>>>:

位运算符
“>>” 右移,高位补符号位,右移1位表示除2 (若值为正,则在高位插入0;若值为负,则在高位插入1)
“>>>” 无符号右移,高位补0(Java独有,无论正负,都在高位插入0)
“<<” 左移,左移1为表示乘2

负数的补码表示:
正数的补码与原码相同,负数的补码为对该数的原码除符号位外各位取反,然后在最后一位加1.
-5 在计算机中表达为:11111111 11111111 11111111 11111011。转换为十六进制:0xFFFFFFFB。

Runtime: 9 ms

class Solution {
    public String toHex(int num) {
        if(num == 0) return "0";
        char[] Hex = {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
        String res = "";
        while(num != 0){
            res = Hex[num & 15] + res; //15 is a mask : '1111'
            num = num >>> 4;
        }
        return res;
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 14,358评论 0 33
  • 一、二进制:所谓二进制就是逢二进一 (0,1), 因为使用二进制只有 0, 1 两个数,简单,易于电子方式实现 ...
    hello大象阅读 8,866评论 0 1
  • 二进制转十进制 0011 10012^(6-1) + 2^(5-1) + 2^(4-1) + 2^(1-1) = ...
    u14e阅读 5,114评论 0 1
  • Locks:1.Table Lock:that maybe lock all table.you can usin...
    perryn阅读 2,118评论 0 0
  • 现在特别的想睡着 眼睛特别的痒 天气也很热 一直在流汗也在流眼泪 我有很多话 可我真的很懒 懒到不说 我毒舌腹黑冷...
    没有秘密的人不可爱阅读 1,166评论 0 0

友情链接更多精彩内容