0%

【Coding!】Reverse Integer

原题:

Given a 32-bit signed integer, reverse digits of an integer.

Example 1:

1
2
Input: 123
Output: 321

Example 2:

1
2
Input: -123
Output: -321

Example 3:

1
2
Input: 120
Output: 21

Note: Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

需求分析:

  1. 输入一个数,输出它的位数倒置数(123→321)
  2. 倒置溢出时,输出为0
  3. 负数倒置仍为负数

我的答案:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
public class Solution {
public int Reverse(int x) {
Queue<int> queue=new Queue<int>();
bool isNegative = checkNegative(ref x);
int result=0;
for(;;)
{
if(x==0)break;
queue.Enqueue(pushIntger(ref x));
}
for(;;)
{
if(queue.Count()==0)break;
if(!popIntger(ref result,queue.Dequeue())){
result=0;
break;
}
}
return isNegative?-result:result;
}

public bool checkNegative(ref int num)
{
bool isNegative = false;
if (num < 0)
{
isNegative = true;
if (num == Int32.MinValue) num = 0;
else num = Math.Abs(num);
}

return isNegative;
}

public int pushIntger(ref int num)
{
int temp=num%10;
num/=10;
return temp;
}

public bool popIntger(ref int num,int pop)
{
if(num>(Int32.MaxValue/10))return false;
else if(num==(Int32.MaxValue/10)&&pop>7)return false;
else {
num=num*10+pop;
return true;
}
}
}
//44ms,15M

原题答案:

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
public int reverse(int x) {
int rev = 0;
while (x != 0) {
int pop = x % 10;
x /= 10;
if (rev > Integer.MAX_VALUE/10 (rev == Integer.MAX_VALUE / 10 && pop > 7)) return 0;
if (rev < Integer.MIN_VALUE/10 (rev == Integer.MIN_VALUE / 10 && pop < -8)) return 0;
rev = rev * 10 + pop;
}
return rev;
}
}