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

CAN通信的数据帧和远程帧

CloudCompare&PCL ICP配准(点到面)

win10系统重装,无法登录进行同步的情况下chrome数据恢复

重磅消息 | Authing 实现与西门子低代码平台的集成

通讯录(静态版)(C语言)(VS)

MySQL调优

新一代超安全蜂窝电池, 思皓爱跑上市13.99万元起售

The CAN communication standard frame and extended frame is introduced
![[Open class preview]: Research and application of super-resolution technology in the field of video image quality enhancement](/img/fc/cd859efa69fa7b45f173de74c04858.png)
[Open class preview]: Research and application of super-resolution technology in the field of video image quality enhancement

CAN通信标准帧和扩展帧介绍
随机推荐
How to successfully pass the CKA exam?
SCHEMA解惑
Tencent Cloud Native: Service Mesh Practice of Areaki Mesh in the 2022 Winter Olympics Video Live Application
How do programmers solve online problems gracefully?
pandas连接oracle数据库并拉取表中数据到dataframe中、筛选当前时间(sysdate)到一个小时之前的所有数据(筛选一个小时的范围数据)
This article will take you to thoroughly clarify the working mechanism of certificates in Isito
MarkDown公式指导手册
Sparse representation - study notes
稀疏表示--学习笔记
如何使用 Authing 单点登录,集成 Discourse 论坛?
STM32 CAN过滤器配置详解
Aeraki Mesh became CNCF sandbox project
SQL函数 STR
JS数据类型转换完全攻略
win10系统重装,无法登录进行同步的情况下chrome数据恢复
实现集中式身份认证管理的案例
【云享新鲜】社区周刊·Vol.73- DTSE Tech Talk:1小时深度解读SaaS应用系统设计
markdown常用数学符号cov(markdown求和符号)
Complete Raiders of JS Data Type Conversion
快速幂---学习笔记