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:
-1 Output:
"ffffffff"

记住要delete begining 0

 public class Solution {
public String toHex(int num) {
StringBuffer res = new StringBuffer();
String[] charMap = new String[]{"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"};
for (int i=0; i<8; i++) {
int number = num & (0b1111);
num = num >>> 4;
res.insert(0, charMap[number]);
}
while (res.charAt(0)=='0' && res.length()>1) res.deleteCharAt(0);
return res.toString();
}
}

要记住单独处理 num == 0的情况

 public class Solution {
public String toHex(int num) {
if (num == 0) return "0";
StringBuffer res = new StringBuffer();
String[] charMap = new String[]{"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"};
while (num != 0) {
int number = num & (0b1111);
num = num >>> 4;
res.insert(0, charMap[number]);
}
return res.toString();
}
}

最新文章

  1. Python: 字典的基本操作
  2. MySql安装出现问题---无服务,修改密码
  3. SercureCRT无法正常连接Ubuntu14.0.4.1的解决办法
  4. 引水入城(codevs 1066)
  5. C基础--关于typedef的用法总结
  6. CSS盒模型简单用法
  7. *[hackerrank]Lexicographic paths
  8. Android Studio 安装
  9. Android最新支持包Design简介
  10. XAF-BI.Dashboard模块概述 web/win
  11. QQ路径
  12. Chapter 4 Invitations——2
  13. JavaScript易错知识点整理[转]
  14. Java语法基础常见疑惑解答8,16,17,21图片补充
  15. nvidia-docker2配置与NVIDIA驱动安装
  16. double compare 0
  17. 力扣(LeetCode) 961. 重复 N 次的元素
  18. 在线团队协作工具+在线UML工具
  19. 大型发布会现场的 Wi-Fi 应该如何搭建(密集人群部署wifi抗干扰)?
  20. presto + slider 提交计算至yarn

热门文章

  1. embody the data item with the ability to control access to itself
  2. Deep_learning
  3. php javascript C 变量环境 块级作用域
  4. Java中的可变参数以及foreach语句
  5. html EL表达式抬头
  6. 【转】C# 解析JSON格式数据
  7. Compiling Inkscape on Windows
  8. A+Bproblem
  9. 【C++】动态内存与智能指针
  10. TCP/IP和HTTP的举例理解