Leetcode Convert a Number to Hexadecimal 405

原创 2017年01月03日 16:42:44

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”

题目链接

主要考虑负数的情况,这里使用逻辑移位

class Solution {
public:
    string toHex(int num) {
        if(num==0) return "0";

        string trans[]={"0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"};

        string ans;

        while(num){
            ans=trans[num & 0xf]+ans;
            num=(unsigned)num >> 4;
        }

        return ans;
    }
};
版权声明:本文为博主原创文章,未经博主允许不得转载。

相关文章推荐

[leetcode: Python]405. Convert a Number to Hexadecimal

Title: Given an integer, write an algorithm to convert it to hexadecimal. For negative integer, two...
  • NXHYD
  • NXHYD
  • 2017年05月16日 17:18
  • 174

LeetCode 405 Convert a Number to Hexadecimal

给一个int的整型数,需要将其转化为16进制表示的字符串,要求负数用补码来表示。给出了四点注意事项: 所有字母a-f全部小写。 不允许前置0,除非值为0. 所给的数保证在32位int的范围内。 不得使...

[LeetCode]405. Convert a Number to Hexadecimal(32位有符号整数转化为十六进制)

405. Convert a Number to Hexadecimal原题链接 Given an integer, write an algorithm to convert it to hexa...

[leetcode]: 405. Convert a Number to Hexadecimal

1.题目Given an integer, write an algorithm to convert it to hexadecimal. For negative integer, two’s c...

LeetCode 405. Convert a Number to Hexadecimal 解题报告

LeetCode 405. Convert a Number to Hexadecimal 解题报告

【LeetCode】405 Convert a Number to Hexadecimal (java实现)

原题链接https://leetcode.com/problems/convert-a-number-to-hexadecimal/原题Given an integer, write an algor...
  • styshoo
  • styshoo
  • 2016年11月09日 23:33
  • 1148

405. Convert a Number to Hexadecimal

强制转换成无符号整数,10进制数变成16进制

[Leetcode] Convert Sorted List to Binary Search Tree Solution

Given a singly linked list where elements are sorted in ascending order, convert it to a height bala...

LeetCode-Convert Sorted List to Binary Search Tree

/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode...

leetcode -day22 Binary Tree Level Order Traversal II & Convert Sorted Array to Binary Search Tree

1、  Binary Tree Level Order Traversal II Given a binary tree, return the bottom-up level order tr...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:Leetcode Convert a Number to Hexadecimal 405
举报原因:
原因补充:

(最多只允许输入30个字)