当前位置:网站首页>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();
}
}
边栏推荐
- .NET性能优化-使用SourceGenerator-Logger记录日志
- JS数据类型转换完全攻略
- 关于亚马逊测评,你了解多少?
- 腾讯云原生:Areaki Mesh 在 2022 冬奥会视频直播应用中的服务网格实践
- (ES6以上以及TS) Map对象转数组
- R language ggplot2 visualization: use the ggdensity function of the ggpubr package to visualize density plots, use the stat_central_tendency function to add mean vertical lines to the density and cust
- Meshlab&Open3D SOR滤波
- 【面试高频题】难度 1.5/5,二分经典运用题
- (ES6 and above and TS) Map object to array
- 一文带你读懂云原生、微服务与高可用
猜你喜欢
[5 days countdown] to explore the secret behind the great quality promotion, gift waiting for you to take of $one thousand
【倒计时5天】探索音画质量提升背后的秘密,千元大礼等你来拿
leetcode/子矩阵元素和
重磅消息 | Authing 实现与西门子低代码平台的集成
这项工作事关中小学生生命安全!五部门作出联合部署
安装apex报错
How to use DevExpress controls to draw flowcharts?After reading this article, you will understand!
稀疏表示--学习笔记
故障007:dexp导数莫名中断
Favorites|Mechanical Engineer Interview Frequently Asked Questions
随机推荐
Sparse representation - study notes
【公开课预告】:超分辨率技术在视频画质增强领域的研究与应用
深入解析volatile关键字
This article will take you to thoroughly clarify the working mechanism of certificates in Isito
CloudCompare&PCL ICP配准(点到面)
[CLion] CLion always prompts "This file does not belong to any project target xxx" solution
【倒计时5天】探索音画质量提升背后的秘密,千元大礼等你来拿
Istio Meetup China:全栈服务网格 - Aeraki 助你在 Istio 服务网格中管理任何七层流量
[Nodejs] node的fs模块
表连接详解
CAN通信标准帧和扩展帧介绍
库函数的模拟实现(strlen)(strcpy)(strcat)(strcmp)(strstr)(memcpy)(memmove)(C语言)(VS)
蔚来又一新品牌披露:产品价格低于20万
bpmn-process-designer基础上进行自定义样式(工具、元素、菜单)
SQL函数 %SQLSTRING
sql中ddl和dml(数据库表与视图的区别)
R语言ggplot2可视化:使用ggpubr包的geom_exec函数执行geom_*函数(没有任何参数需要放置在aes中)
通配符SSL证书不支持多域名吗?
ECCV22|只能11%的参数就能优于Swin,微软提出快速预训练蒸馏方法TinyViT
ddl and dml in sql (the difference between database table and view)