The seventh title integer power button reverse

Topic Overview

  • Title: The seventh title
  • Difficulty: Easy
  • Content: Gives a 32-bit signed integer, you need this integer numbers on each inverted. Example 1:

    Input: 123 Output: 321

    Example 2:

    Input: Output -123: -321

    Example 3:

    Input: 120 Output: 21

    note:

    Suppose we have an environment can only store a 32-bit signed integer, then the value range of [-231 231--1]. Please According to this hypothesis, if integer overflow after reverse it returns 0.

    Source: stay button (LeetCode) link: https: //leetcode-cn.com/problems/reverse-integer

The first idea

The first considers only three integers, not thinking the range of integer problems.

Code

class Solution {
public:
    int reverse(int x) {
    int bai;
    int shi;
    int ge,y;
    bai = x/100;
    shi = x/10%10;
    ge = x%10;
    y=ge*100+shi*10+bai;
    if(x<0)
    {
        return y=-y;
    }
        return y;
    }  
};

Test Submit

The test results can only meet three integers, does not satisfy the other conditions

analysis

There are two points title Note:

  1. 32-bit signed integer, the range from the negative 2,147,483,648 worth (represented by Int_MIN constant) to the positive 2,147,483,647 (represented by Int_MAx constant) values, not just three integer
  2. Reverse way

Improve

  1. Number -9 to 9, can be directly output

  2. Overflow numbers, 0 is returned;

  3. The intermediate portion using a while loop to solve.

    ①. After a number of defining a new long integer to store reverse

    ②. Of x modulo operation performed, then the structures are passed to y. For example: 321, modulo 10 for 1, 1 is transmitted to the y, x rounded to 10, 32; in the second cycle, the y * 10, is equal to 10, then repeat the operation, y = 12, x = 3, y = 123, x = 0, then the loop is exited

Improved Code

class Solution {
public:
    int reverse(int x) {
        long y=0;
        if(x>-9&&x<9){
            return x;
        }
        
        
        else{
            while(x){
                y=y*10;
                 if(y<=INT_MIN||y>=INT_MAX)
                return 0;//溢出
                y=y+x%10;
                x=x/10;
                
            }
            return y;
        }
    }
};


Improved Submit

img_@~L5.png)

Harvest summary

The subject is relatively simple, but there are details that need to be considered, such as overflow problems, as well as the code to simplify the problem.

Guess you like

Origin www.cnblogs.com/HanLongfeng/p/11874116.html