Easy CHALLENGE
Reverse Number
Given an integer, reverse its digits.Logical Approach_
1
Initialize reversed_num = 0.2
While input num is not 0:3
- Get last digit using num % 10.4
- Multiply reversed_num by 10 and add the digit.5
- Remove last digit from num using floor division by 10.Variations Hub_
Reverse a number and handle 32-bit integer overflow (LeetCode variant).
Check if reversing a number results in the same number (another way for palindrome).
Implementation Protocol (JS)
function reverseNumber(num) {
let reversed = 0;
let sign = num < 0 ? -1 : 1;
num = Math.abs(num);
while (num > 0) {
reversed = (reversed * 10) + (num % 10);
num = Math.floor(num / 10);
}
return reversed * sign;
}Line-by-Line Breakdown_
Point 1
Line 3-4: Handle negative numbers by storing the sign and using absolute values.
Point 2
Line 7: Shift existing reversed digits left by multiplying by 10 and add the new digit.
Point 3
Line 8: Update input number by removing the unit place digit.
Point 4
Line 11: Restore the original sign to the reversed result.