当前位置:网站首页>LeetCode_位运算_简单_405.数字转换为十六进制数
LeetCode_位运算_简单_405.数字转换为十六进制数
2022-08-01 12:21:00 【小城老街】
1.题目
给定一个整数,编写一个算法将这个数转换为十六进制数。对于负整数,我们通常使用补码运算方法。
注意:
① 十六进制中所有字母 (a - f) 都必须是小写。
② 十六进制字符串中不能包含多余的前导零。如果要转化的数为 0,那么以单个字符 ‘0’ 来表示;对于其他情况,十六进制字符串中的第一个字符将不会是 0 字符。
③ 给定的数确保在 32 位有符号整数范围内。
④ 不能使用任何由库提供的将数字直接转换或格式化为十六进制的方法。
示例 1:
输入:
26
输出:
“1a”
示例 2:
输入:
-1
输出:
“ffffffff”
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/convert-a-number-to-hexadecimal
2.思路
(1)位运算
3.代码实现(Java)
//思路1————位运算
class Solution {
public String toHex(int num) {
if (num == 0) {
return "0";
}
StringBuilder builder = new StringBuilder();
// int 类型的二进制整数有 32 位,故只需遍历 8 组 4 个二进制位
for (int i = 7; i >= 0; i--) {
// 从高位开始转换
int value = (num >> (4 * i)) & 0xf;
if (builder.length() > 0 || value > 0) {
char digit;
if (value < 10) {
digit = (char) ('0' + value);
} else {
digit = (char)('a' + value - 10);
}
builder.append(digit);
}
}
return builder.toString();
}
}
边栏推荐
- How to get the address of WeChat video account (link address of WeChat public account)
- 测试发文
- Favorites|Mechanical Engineer Interview Frequently Asked Questions
- 通配符SSL证书不支持多域名吗?
- (ES6 and above and TS) Map object to array
- pandas connects to the oracle database and pulls the data in the table into the dataframe, filters all the data from the current time (sysdate) to one hour ago (filters the range data of one hour)
- formatdatetime函数 mysql(date sub函数)
- .NET性能优化-使用SourceGenerator-Logger记录日志
- 重磅消息 | Authing 实现与西门子低代码平台的集成
- js中常用追加元素的几种方法:append,appendTo,after,before,insertAfter,insertBefore,appendChild
猜你喜欢
Pytest电商项目实战(下)
Dameng replaces the officially authorized dm.key
阿里云官方 Redis 开发规范
C#/VB.NET 将PPT或PPTX转换为图像
字体反爬之好租
【StoneDB Class】入门第二课:StoneDB 整体架构解析
通讯录(静态版)(C语言)(VS)
[5 days countdown] to explore the secret behind the great quality promotion, gift waiting for you to take of $one thousand
MarkDown公式指导手册
Programmer's self-cultivation
随机推荐
Istio Meetup China: Full Stack Service Mesh - Aeraki Helps You Manage Any Layer 7 Traffic in an Istio Service Mesh
SCHEMA解惑
Complete Raiders of JS Data Type Conversion
Tencent Cloud Native: Service Mesh Practice of Areaki Mesh in the 2022 Winter Olympics Video Live Application
formatdatetime function mysql (date sub function)
博弈论(Depu)与孙子兵法(42/100)
易周金融分析 | 银行ATM机智能化改造提速;互联网贷款新规带来挑战
Data frame and remote frame of CAN communication
[Open class preview]: Research and application of super-resolution technology in the field of video image quality enhancement
这项工作事关中小学生生命安全!五部门作出联合部署
Grafana9.0发布,Prometheus和Loki查询生成器、全新导航、热图面板等新功能!
js中常用追加元素的几种方法:append,appendTo,after,before,insertAfter,insertBefore,appendChild
判断JS数据类型的四种方法
Qt get all files in a folder
实现集中式身份认证管理的案例
C#/VB.NET 将PPT或PPTX转换为图像
如何成功通过 CKA 考试?
pandas连接oracle数据库并拉取表中数据到dataframe中、筛选当前时间(sysdate)到一个小时之前的所有数据(筛选一个小时的范围数据)
【云享新鲜】社区周刊·Vol.73- DTSE Tech Talk:1小时深度解读SaaS应用系统设计
[Cloud Enjoying Freshness] Community Weekly Vol.73- DTSE Tech Talk: 1 hour in-depth interpretation of SaaS application system design