Leetcode Convert a number to hexadecimal

Source: Internet
Author: User

The original title link is here: https://leetcode.com/problems/convert-a-number-to-hexadecimal/

Topic:

Given an integer, write a algorithm to convert it to hexadecimal. For negative integer, the complement method is used.

Note:

    1. All letters in hexadecimal ( a-f ) must is in lowercase.
    2. The hexadecimal string must not contain extra leading 0 s. If the number is zero, it's represented by a single zero character ‘0‘ ; otherwise, the first character in the HEXADECIM Al string would not be the zero character.
    3. The given number is guaranteed to fit within the range of a 32-bit signed integer.
    4. You must don't use any method provided by the library which converts/formats the number to hex directly.

Example 1:

Input:26output: "1a"

Example 2:

Input:-1output: "FFFFFFFF"
Exercises

Each of the 4 bits consists of a hexadecimal digit, each taking out the last 4 bits and 1111 doing bit arithmetic & getting a digit.

Num moves right 4 bits, here with >>> instead of >>. e.g.-1 of two ' s complement is represented as FFFFFFFF, 32 bits are all 1 bit. If the 1 bit with >> first does not move, the condition num!=0 of the while loop does not appear.

Time Complexity:o (1). Space:o (1).

AC Java:

1  Public classSolution {2      PublicString Tohex (intnum) {3         if(num = = 0){4             return"0";5         }6         7StringBuilder SB =NewStringBuilder ();8          while(num! = 0){9             intdigit = num & 0xf;TenSb.insert (0, digit<10?) (Char) (digit+ ' 0 '): (Char) (digit-10+ ' a ')); OneNum >>>= 4; A         } -         returnsb.tostring (); -     } the}

Leetcode Convert a number to hexadecimal

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.