题目: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(int x) { 2 List<Integer> ans = new ArrayList<Integer>(); 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 return y; 28 }
结果:1027 / 1032 test cases passed.
Input:1534236469
Output:1056389759
Expected:0
意思是反转之后需要判断是否溢出。弄了半天都没思绪,因为反转后一位一位乘以10后就直接溢出然后变为另外一个值,不好比较是否越界。。。。
原谅我这个笨脑阔吧