题目:Reverse Integer
难度:Easy
题目内容:
Given a 32-bit signed integer, reverse digits of an integer.
Note:
Assume we are dealing with an environment which could only hold integers within the 32-bit signed integer range. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
翻译:给定一个32位签名整数,一个整数的反向数字。
注意:
假设我们正在处理一个只能容纳32位的整形数值。出于这个问题的目的,当反转整数溢位时函数返回0。
Example 1:
Input: 123
Output: 321
Example 2:
Input: -123
Output: -321
Example 3:
Input: 120
Output: 21
我的思路:用List将数值从低位依次取出到高位,用list的第一个记录此整数的符号。最后输出的时候用一个boolean来判断是否前面全为零,然后跳过此零。
我的代码:
1 public int reverse(intx) {2 List ans = new ArrayList();3 if (x < 0) {4 ans.add(0);5 x = -x;6 } else if (x > 0) {7 ans.add(1);8 } else{9 return 0;10 }11 while (x != 0) {12 ans.add(x%10);13 x = x / 10;14 }15 int y = 0;16 boolean tag = false;17 for (int i = 1;i < ans.size(); i++) {18 if (tag == false && ans.get(i) == 0) {19 continue;20 } else{21 tag = true;22 }23 y +=ans.get(i);24 if (i < ans.size() - 1) y *= 10;25 }26 y = ans.get(0) == 1 ? y : -y;27 returny;28 }
结果:1027 / 1032 test cases passed.
Input:1534236469
Output:1056389759
Expected:0
意思是反转之后需要判断是否溢出。弄了半天都没思绪,因为反转后一位一位乘以10后就直接溢出然后变为另外一个值,不好比较是否越界。。。。
原谅我这个笨脑阔吧??
编程中问题:
1、boolean类型再赋值的时候不小心用了 == ,结果LeetCode报错:not a Statement
答案:
1 public int reverse(intx) {2 int result = 0;3 while (x != 0)4 {5 int tail = x % 10;6 int newResult = result * 10 +tail;7 if ((newResult - tail) / 10 !=result)8 { return 0; }9 result =newResult;10 x = x / 10;11 }12 returnresult;13 }
还有没有天理了。。。。13行就搞定了?!
答案思路:
1、因为负数求余数和除以10后还是负数,所以并不需要将符号进行记录。
2、因为若当前反转第一个数为零,乘以10还是零,所以也不需要用list进行记录。
3、因为乘以10再加上一个值后可能溢出无法与max值相比较,那么就反过来用(max-tail)/ 10 与当前值进行比较!哎 我真笨的可以。。
4、可以直接用新值反推旧值进行比较,变了说明,这样就不用对tail进行正负判断(当tail为负的时候就应该是(min-tail)/10 > result 为正应该是(max-tail)/10 < result )