1 Problem

LeetCode 7 Reverse Integer

Given a 32-bit signed integer, reverse digits of an integer.

Example 1:

Input: 123
Output: 321

Example 2:

Input: -123
Output: -321

Example 3:

Input: 120
Output: 21

Note:
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231,  231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

2 Notes

2.1

A easy iterative way of reverse a integer is the following.

Input:  num
(1) Initialize rev_num = 0
(2) Loop while num > 0
     (a) Multiply rev_num by 10 and add remainder of num  
          divide by 10 to rev_num
               rev_num = rev_num*10 + num%10;
     (b) Divide num by 10
(3) Return rev_num

2.2

Considering about checking if overflow, someone thinks we could revoke the step of updating. But I find that in some condition that involve negative numbers, this method does not work. And someone solves this by comparing the number without the lowest digit with the maximum or minimum value mod 10. However, that is not precise. Therefore, in my opinion, the most reliable solution is using “long” data type.

3 Codes

class Solution {
    public int reverse(int x) {
        long res=0;
        while(x!=0)
        {
            res=res*10+x%10;
            if(res>Integer.MAX_VALUE||res<Integer.MIN_VALUE) return 0;
            x=x/10;
        }
        return (int)res;
    }
}

Reference

[1] https://leetcode.com/problems/reverse-integer/solution/

[2] https://www.geeksforgeeks.org/write-a-c-program-to-reverse-digits-of-a-number/

Leave a Reply

Your email address will not be published. Required fields are marked *