Flip leetcode7 integer (integer simple algorithm for bit operation)

Description [title]

Gives a 32-bit signed integer, you need this integer number on each inverted.

Example 1:

Input: 123
Output: 321
 Example 2:

Input: -123
Output: -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.

【answer】

Reverse the positive and negative there is a new number, the original number from the last few years began to accumulate in the new

That is, + = x% 10

After processing the first number, after the second to be processed, i.e. x% 100, if the addition cycle, the cycle conditions are set:

x / 10

For integer re returned each time into a new number, the original number left one, that is:

re * 10

For the judge spilled my idea from the beginning was directly int overflow, after the overflow re inverted positive and negative values, then only we need to determine the different positive and negative values of the original X and can be re

But it leetcode error! ! ! It will not let me natural overflow! ! !

Ok I bow to the platform

The next step is arranged to re long int is greater than 2 ^ determines 31--1 or less than -2 ^ 31 + 1

1 int reverse(int x){
2     long int re = 0;
3     for(; x; x /= 10)
4         re = re * 10 + x % 10;
5     if (re > 2147483647 || re < -2147483648)
6         return 0;
7     else
8         return re;
9 }

As Code

Results of the:
by
When execution: 0 ms, defeated 100.00% of all users in C submission
Memory consumption: 5.9 MB, defeated 100.00% of all users in C submission

 

I was a novice programmer, I slowly start from the simplest of simple questions, although it is simple, but I have to do our best every

Guess you like

Origin www.cnblogs.com/jhjgarden/p/12610044.html