Convert a Number to Hexadecimal
Real-world version: Writing a Signed Reading in Base SixteenThe statement here is our own: the same inputs, outputs and technique.
A reading num is a whole number that fits in thirty-two bits.
Write it in base sixteen, using '0' through '9' and then the lowercase letters 'a' through 'f'. A negative reading is written as its pattern over thirty-two bits taken as an unsigned number, which is the reading plus two raised to the thirty-second. Write no leading zero, except that the reading 0 is written as the single character "0".
Return that spelling.
Examples
Example 1
- Input
- num = 255
- Output
- "ff"
Two hundred and fifty-five is fifteen sixteens plus fifteen, and fifteen is written as the letter f.
Example 2
- Input
- num = 0
- Output
- "0"
The reading is nothing, which is written as a single zero rather than as no digits at all.
Example 3
- Input
- num = -2147483648
- Output
- "80000000"
Adding two raised to the thirty-second turns this reading into two raised to the thirty-first, which in base sixteen is an eight followed by seven zeros.
Constraints
- -2^31 <= num <= 2^31 - 1
The signature
The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.
def to_hex(num: int) -> str:public String toHex(int num)Checking your plan…
How this problem was checked
- Passed: Reference solution run against 15 test cases: 15 passed
- Passed: 3 worked examples confirmed by running the code
- Passed: 0 eight-word sequences shared with the parent problem's text
- Passed: Agrees with an independent brute-force solution on random inputs
- Passed: Test set shown to catch deliberately broken solutions
- Passed: Reviewed by a separate quality pass
- Passed: Function arity matches the parent problem's