|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
- Given a 32-bit signed integer, reverse digits of an integer.
- Example 1:
- Input: 123
- Output: 321
- Example 2:
- Input: -123
- Output: -321
- Example 3:
- 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.
复制代码
First try
- import java.math.BigInteger;
- class Solution {
- public int reverse(int x) {
- String num = Integer.toString(x);
-
- String result = "";
-
- int len = num.length();
-
- int flag = 0;
-
- if(num.substring(0,1).equals("-")){
-
- flag = 1;
-
- num = num.substring(1,len);
-
- len = len -1;
-
- }
-
- for(int i = 0 ; i< len; i++){
-
- result = num.substring(i,i+1) + result;
- }
-
- BigInteger n = new BigInteger(result);
-
- BigInteger s = new BigInteger("-2147483648");
- BigInteger b = new BigInteger("2147483647");
-
- if(n.compareTo(s)<0 || n.compareTo(b)>0){
-
- return 0;
- }
-
- x = Integer.parseInt(result);
-
- if(flag == 1){
-
- return 0-x;
- }
- else{
-
- return x;
- }
- }
- }
复制代码
Second try.
- class Solution {
- public int reverse(int x) {
-
- long result = 0;
-
- while(x != 0){
-
- result = result * 10 + x % 10;
-
- x = x/10;
- }
-
- if(result > 2147483647 || result < -2147483648 )
- return 0;
-
- return (int)result;
-
- }
- }
复制代码 |
|