[Primary Algorithm] 13. Reverse Integer

topic:

Given a 32 -bit signed integer, invert the numbers in the integer.

Example 1 :

Input: 123 
Output: 321 
 Example 2 :

Input: - 123 
Output: - 321 
Example 3 :

Input: 120 
Output: 21
Notice:

Suppose our environment can only store 32 -bit signed integers whose values ​​are in the range [− 231 ,   2311 ]. According to this assumption, if the inverted integer overflows, 0 is returned .

Problem solving ideas:

1. This question is relatively simple. Directly take out the number on each digit, and then form a new number to complete the problem requirements.

Source code:

class Solution {
public:
    int reverse(int x) {
        int res = 0;
        
        while(x != 0){
            int val = x % 10;
            int tmp = res;
            res = tmp * 10 + val;
            x = x / 10;
            if(res / 10 != tmp) return 0;
        }
        
        return res;
    }
};

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325174406&siteId=291194637