LeetCode 7:Reverse Integer

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 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.

数字颠倒位置,这个比较简单

先来一个奇葩的做法,先把整数变成字符串,然后颠倒一把,然后转变成一个long型的整数,假如出现越界直接返回0,没越界的话,强制转型返回int即可

七拼八凑最终还是Ok的,搞笑方法如下

package com.maoxiaomeng;

/**
* @author lihui
* @date 2018/3/25 22:31
*/
public class Solution {

public int reverse(int x) {

if (x == 0) {
return x;
}

while (x % 10 == 0 && x != 0) {
x = x / 10;
}

String s = x + "";
if (s.charAt(0) == '-') {
s = '-' + new StringBuffer(s.substring(1, s.length())).reverse().toString();
} else {
s = new StringBuffer(s).reverse().toString();
}

long temp = Long.valueOf(s);
if (temp > Integer.MAX_VALUE || temp < Integer.MIN_VALUE) {
temp = 0;
}
return (int)temp;
}
}

下面是正规方法

比如1234 = ((1 * 10 + 2) * 10 + 3) * 10 + 4

那么倒序就是4321 = ((4 * 10 + 3) * 10 + 2) * 10 + 1

得到temp = temp * 10 + x % 10,然后x = x / 10

package com.maoxiaomeng;

/**
* @author lihui
* @date 2018/3/25 22:31
*/
public class Solution {

public int reverse(int x) {

long temp = 0;
while (x != 0) {
temp = temp * 10 + x % 10;
x = x / 10;
}

if (temp > Integer.MAX_VALUE || temp < Integer.MIN_VALUE) {
temp = 0;
}
return (int)temp;
}
}

简单多了

发表回复