您的位置:首页 > 其它

LeetCode刷题笔录 Reverse Integer

2014-02-15 13:23 253 查看
Reverse digits of an integer.

Example1: x = 123, return 321

Example2: x = -123, return -321

随手写的一个,正常的读出每一位的数字然后反序:

import java.lang.Math;
public class Solution {
public int reverse(int x) {

boolean isNegative = isNegative(x);
x = Math.abs(x);

int numOfDigits = calDigits(x);
int[] digits = new int[numOfDigits];
for(int i = 0; i < numOfDigits; i++){
digits[i] = x % 10;
x /= 10;
}

int result = 0;
int pow = pow(10, numOfDigits - 1);
for(int i = 0; i < numOfDigits; i++){
result += digits[i] * pow;
pow /= 10;
}
if(isNegative){
result = -result;
}
return result;
}

public int pow(int a, int b){
int result = a;
if (b == 0) {
return 1;
}
for(int i = 1; i < b; i++){
result *= a;
}
return result;
}
public boolean isNegative(int x){
if(x < 0) return true;
else return false;
}

public int calDigits(int x){
int numOfDigits = 1;
while(x > 10){
numOfDigits++;
x /= 10;
}
return numOfDigits;
}
}


转成字符串可以调用StringBuilder类的reverse函数,属于作弊,不提了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: