博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
leetcode 405. Convert a Number to Hexadecimal | &0xf和>>4
阅读量:7104 次
发布时间:2019-06-28

本文共 1605 字,大约阅读时间需要 5 分钟。

Description

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 0s. 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.
Example 1:

Input:

26

Output:

"1a"
Example 2:

Input:

-1

Output:

"ffffffff"

My solution

很自然的想到>>4bit方式, &0xf相当于对16取余, 用unordered_map把11,12,13,14,15转为abcdef, 但是细节处理仍有待进步, 具体参见下文discuss优秀答案(基本原理一致).

class Solution {public:    string toHex(int num) {        if (num == 0) return "0";        string res;        unordered_map
mp; mp[10] = 'a'; mp[11] = 'b'; mp[12] = 'c'; mp[13] = 'd'; mp[14] = 'e'; mp[15] = 'f'; int last, cnt = 0; while (num && ++cnt <= 8) { last = num & 0xf; res = last > 9 ? mp[last] + res : to_string(last) + res; num >>= 4; } return res; }};

Discuss

const string HEX = "0123456789abcdef";class Solution {public:    string toHex(int num) {        if (num == 0) return "0";        string result;        int count = 0;        while (num && count++ < 8) {            result = HEX[(num & 0xf)] + result;            num >>= 4;        }        return result;    }};

Reference

转载地址:http://ouuhl.baihongyu.com/

你可能感兴趣的文章
arduino 配eclipse的博客,有空看下
查看>>
linux下用mail命令发送邮件
查看>>
MongoDB复制集部署和基本管理
查看>>
单链表面试题(二)从头到尾打印单链表
查看>>
strcmp()
查看>>
CET,UTC,GMT,CST几种常见时间概述
查看>>
开源数字媒体资产管理系统:Razuna安装方法
查看>>
洛克菲勒给儿子的38封信(前14封选摘)
查看>>
揭秘双11“某东”背后的架构实战
查看>>
redis高可用之redis sentinel(哨兵)的搭建以及应用
查看>>
spring-boot+spring-session集成
查看>>
vmware挂载磁盘脱机解决方案
查看>>
多点触控实现图面的放大与缩小
查看>>
Android开发小记--开发实用工具类--数据库操作类
查看>>
memcached总结
查看>>
http://blog.itpub.net/28929558/viewspace-1473102
查看>>
八款常用的 Python GUI 开发框架推荐
查看>>
H3C实验20-OSPF
查看>>
xxx is not in the sudoers file
查看>>
maven 镜像网站
查看>>