405. Convert a Number to Hexadecimal

Given an integer, write an algorithm to convert it to hexadecimal. For negative integer, two’s complement method is used.

Note:

  1. All letters in hexadecimal (a-f) must be in lowercase.
  2. 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.
  3. The given number is guaranteed to fit within the range of a 32-bit signed integer.
  4. 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:
-1

Output:
"ffffffff"
含义:将整数转换为16进制字符串

复制代码
 1     public String toHex(int num) {
 2 //        每次取出最右边四位,如果其大于等于10,找到对应的字母加入结果,反之则将对应的数字加入结果,然后num像右平移四位,
 3 //        循环停止的条件是num为0,或者是已经循环了7次(java中int是32位,移了7次以后只剩4位了)
 4         String res = "", str = "0123456789abcdef";
 5         int cnt = 0;
 6         while (num != 0 && cnt++ < 8) {
 7             res = str.charAt((num & 0xf)) + res;
 8             num >>= 4;
 9         }
10         return res.isEmpty() ? "0" : res;  
11     }
复制代码

 

posted @   daniel456  阅读(115)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
点击右上角即可分享
微信分享提示