当前位置:网站首页>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();
}
}
边栏推荐
猜你喜欢
随机推荐
如何将第三方服务中心注册集成到 Istio ?
数据湖 delta lake和spark版本对应关系
Ts-Map 类的使用
库函数的模拟实现(strlen)(strcpy)(strcat)(strcmp)(strstr)(memcpy)(memmove)(C语言)(VS)
R语言ggplot2可视化:使用ggpubr包的ggdensity函数可视化密度图、使用stat_central_tendency函数在密度中添加均值竖线并自定义线条类型
并发编程10大坑,你踩过几个?
Envoy source code flow chart
浏览器存储
Visualization of lag correlation of two time series data in R language: use the ccf function of the forecast package to draw the cross-correlation function, and analyze the lag correlation according t
How to Integrate Your Service Registry with Istio?
Istio Meetup China: Full Stack Service Mesh - Aeraki Helps You Manage Any Layer 7 Traffic in an Istio Service Mesh
bat倒计时代码
如何成功通过 CKA 考试?
SCHEMA解惑
[Cloud Enjoying Freshness] Community Weekly Vol.73- DTSE Tech Talk: 1 hour in-depth interpretation of SaaS application system design
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)
C#/VB.NET 将PPT或PPTX转换为图像
Js手写函数之new的模拟实现
Detailed explanation of table join
MarkDown公式指导手册







