当前位置:网站首页>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();
}
}
边栏推荐
猜你喜欢

Data frame and remote frame of CAN communication

找出相同属性值的对象 累加数量 汇总
![[5 days countdown] to explore the secret behind the great quality promotion, gift waiting for you to take of $one thousand](/img/de/1e6069e84183d1400c90a6ec574f72.png)
[5 days countdown] to explore the secret behind the great quality promotion, gift waiting for you to take of $one thousand

达梦更换正式授权dm.key

程序员的自我修养

Audio and Video Technology Development Weekly | 256

Dameng replaces the officially authorized dm.key

Sparse representation - study notes

将同级数据处理成树形数据

重庆市大力实施智能建造,推动建筑业数字化转型,助力“建造强市”
随机推荐
R language fitting ARIMA model: use the auto.arima function in the forecast package to automatically search for the best parameter combination, model order (p, d, q), set the seasonal parameter to spe
markdown常用数学符号cov(markdown求和符号)
[Cloud Enjoying Freshness] Community Weekly Vol.73- DTSE Tech Talk: 1 hour in-depth interpretation of SaaS application system design
【StoneDB Class】入门第二课:StoneDB 整体架构解析
一文带你读懂云原生、微服务与高可用
新一代超安全蜂窝电池, 思皓爱跑上市13.99万元起售
通配符SSL证书不支持多域名吗?
This article will take you to thoroughly clarify the working mechanism of certificates in Isito
Do wildcard SSL certificates not support multiple domains?
易周金融分析 | 银行ATM机智能化改造提速;互联网贷款新规带来挑战
bpmn-process-designer基础上进行自定义样式(工具、元素、菜单)
Detailed explanation of table join
蔚来又一新品牌披露:产品价格低于20万
[Nodejs] fs module of node
pandas连接oracle数据库并拉取表中数据到dataframe中、筛选当前时间(sysdate)到一个小时之前的所有数据(筛选一个小时的范围数据)
win10系统重装,无法登录进行同步的情况下chrome数据恢复
表连接详解
How to successfully pass the CKA exam?
将同级数据处理成树形数据
小程序插件如何帮助开发者受益?