Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save asd1245dss/b0fc6b246de228612732a58b5e6f24f0 to your computer and use it in GitHub Desktop.
Save asd1245dss/b0fc6b246de228612732a58b5e6f24f0 to your computer and use it in GitHub Desktop.
/**
* 整数反转
* @param x 32位的整数
* @return 如果超过最大最小限制,则返回0,否则返回反转之后的数字,符号位不变
*/
private static int reverse(int x) {
boolean negative = false;
final int decimal = 10;
final StringBuilder stringBuilder = new StringBuilder();
if (x < 0) {
x *= -1;
negative = true;
}
for (int bitNum = x % decimal; x > 0; x = x / decimal, bitNum = x % decimal) {
stringBuilder.append(bitNum);
}
final String result = stringBuilder.toString();
if (result.isEmpty()) {
return 0;
}
Long longValue = Long.valueOf(result);
if (longValue > Integer.MAX_VALUE || longValue < Integer.MIN_VALUE) {
return 0;
}
return (negative ? -1 : 1) * Integer.valueOf(result);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment