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