[Algorithm problem solution] LeetCode 7. Integer inversion

topic

Given a 32-bit signed integer, you need to invert the digits on each of the integers.
Assuming that our environment can only store 32-bit signed integers, the value range is [−2^31, 2^31 − 1]. According to this assumption, if the integer overflows after the inversion, it returns 0.

Solution 1

Reversing a number means rebuilding a new number from its ones place. To get the ones digit, use last = num% 10. After that, num = num / 10 is performed, and one digit is discarded. Then use num% 10 to get 10 digits. For the generation of new numbers, you can use result = result * 10 + last. In this way, the single digits obtained each time are placed in the last digit of the result, and gradually become the previous digits as the loop progresses.

Another issue to consider is overflow. Invert an int directly, it is possible to get a number greater than int. So we can use a long variable to store the result. After getting the final result, judge whether it exceeds the range of Int.

In addition, the above solution does not need to consider the problem of negative numbers, because the algorithm is also true for negative numbers.

Code 1

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

Knowledge points

1. The result of the mixed operation of long and int is long, which can be directly assigned to a long variable.
2. Long and int can be directly compared in size
3. The algorithm is also true for negative numbers

Guess you like

Origin blog.csdn.net/vxzhg/article/details/106673473