7. Reverse Integer [E] integer inverted

topic

Given a 32-bit signed integer, reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123,return -321
Example3: x = 120, return 21

C ++ ideas

The key is to judge the overflow.
C ++ knowledge:

  • integer range: \ (- 31 is 2 ^ {} \ SIM 31 is 2 ^ {-1} \)
  • a half machine word short, int is a machine word, long as one or two types of machine word
  • Stoi () character processing function, int converting the digital output into the string, and to check for range, range is within the default range of int, if the runtime error will be out of range

Reverse integer:
reading the current input x by digit modulo operation, the integer s into reverse after the last bit, the new s obtained by adding the last bit of x s * 10, corresponding to the left-x a shift. Through the operation of x = x / 10, so that a right x, x is a number of bits are converted to decimal places cast out, and then take the remainder obtained new digits.
Judge overflow:

  • And INT_MAX, INT_MIN compare
  • Logarithm some calculations, if spilled, then the value for the reverse action and values ​​before the operation is not the same

Thinking 1:
calculated directly or long long long, thus ensuring not overflow, then the number is determined whether the overflow inverted

int reverse(int x){
  long long res=0;
  while(x!=0){
    int t = res * 10 + x % 10;
    if(t /10 != res)
      return 0;
    res = t;
    t /= 10;
  }
  return res;
}

2 idea:
by string conversions, since Stoi () function int for range check, using the exception handling mechanism.

int reverse(int x){
  std::string str = std::to_string(x);
  if(str[0] == '-')
    std::reverse(str.begin()+1,str.end());
  else
    std::reverse(str.begin(),str.end());
  try{
    return stoi(str);
  }
  catch(out_of_range ex){
    return 0;
  }
}

python ideas

python knowledge:

  • Fragmentation string. There are three separate digital indexing operator (:), the first number is the starting value, the default is the starting position of the string, i.e. index 0; end end The second number is the value of the default string character; The third number is the step size, the default is 1.
  • Step is -1, python that is rearwardly
  • python uses a semi-open interval, comprising starting value range, but does not include the final value.

Thinking:
Python int is the long integer, can be determined by a direct comparison of 32-bit size is integer overflow. It is accomplished by reversing the string fragment.

def reverse(self, x):
  if x >= 0:
    s = (int)(str(x)[::-1])  
  else:
    s = -(int)(str(-x)[::-1])
  if s >= -(2**31) and s <= (2**31)-1:
    return s
  else:
    return 0

Guess you like

Origin www.cnblogs.com/Jessey-Ge/p/10993432.html