leetcode 第十六周解题报告
来源:互联网 发布:什么是淘宝流量怎么用 编辑:程序博客网 时间:2024/05/20 15:11
问题描述:
Given an integer, write an algorithm to convert it to hexadecimal. For negative integer, two’s complement method is used.
Note:
- All letters in hexadecimal (
a-f
) must be in lowercase. - The hexadecimal string must not contain extra leading
0
s. If the number is zero, it is represented by a single zero character'0'
; otherwise, the first character in the hexadecimal string will not be the zero character. - The given number is guaranteed to fit within the range of a 32-bit signed integer.
- You must not use any method provided by the library which converts/formats the number to hex directly.
用移位操作将数的每一位取出保存在bool数组里面,再按每四位为一个单元的顺序重新组织十六进制数即可。
代码:
#include<cmath>class Solution {public: string toHex(int num) { char codeT[] = {'0', '1', '2', '3', '4','5', '6','7','8','9','a','b','c','d','e','f' }; if (num == 0) return string("0"); //bool sign = (num > 0 ? true : false); bool bits[32]; for(int i = 31; i >= 0; --i){ bits[31 - i] = num & (1 << i); } string res("00000000"); for(int i = 0; i < 8; ++i){ int tmp = 0; for(int j = 0; j < 4; ++j){ tmp = (tmp << 1) + (int)(bits[i * 4 + j]); } res[i] = codeT[tmp]; } for(int i = 0; i < 8; ++i){ if(res[i] != '0'){ return std::string(res.begin() + i, res.end()); } } }};
阅读全文
0 0
- leetcode 第十六周解题报告
- leetcode第十六周解题总结--图
- leetcode第六周解题报告
- leetcode第七周解题报告
- leetcode十八周解题报告
- leetcode十二周解题报告
- 第十六周往年期末考试题I解题报告
- LeetCode 解题报告索引
- [LeetCode]Permutations,解题报告
- Leetcode Triangle 解题报告
- [LeetCode]Anagrams,解题报告
- leetCode解题报告
- [LeetCode]Candy, 解题报告
- 【LeetCode】Candy 解题报告
- 【LeetCode】Triangle 解题报告
- 【LeetCode】Permutations 解题报告
- LeetCode 解题报告 LinkedListCycleII
- LeetCode 解题报告 Candy
- C语言中的运算符
- C常用库函数实现
- Mysql高级查询-----汇总和分组数据
- memcache
- java反射-有参构造函数初始化对象
- leetcode 第十六周解题报告
- 软件安全复习(GX)
- 自定义view圆形进度条,并改变百分比。
- HTML5总结(二)
- LAN-401信号处理模块
- 关于面向对象体系的总结
- Python访问远程服务器
- 笔记本加装SSD
- 第四届图灵杯-A.谷神的赌博游戏(概率题,排列组合,推公式)