1、整数反转
/**
* 整数反转
* 例:142 ==> 241
*
* 14 2
* 1 24
* 0 241
*
* 存在问题:
* 反转后数据溢出
* int型的数值范围是 -2147483648~2147483647
* @param x
* @return
*/
public int reverse(int x) {
int res = 0;
while (x != 0) {
// 溢出
if ((res * 10) / 10 != res) {
res = 0;
break;
}
res = res * 10 + x % 10;
x = x / 10;
}
return res;
}
2、字符串相加
两个数字类型的字符串,直接转int或者double肯定都放不下,然后求这两个数的和,
返回值还是字符串
/**
* 长字符串相加:
* 12451
* 183
*
*
* 0 4
* 1 3
* 0 6
*
*
* @param num1
* @param num2
* @return
*/
public static String sumTwoString(String num1, String num2) {
StringBuilder result = new StringBuilder(5200);
int carry = 0;
int l1 = num1.length();
int l2 = num2.length();
while(l1>0 || l2 > 0 || carry > 0) {
int tem = carry;
if(l1 > 0) {
l1--;
tem = tem + num1.charAt(l1) - '0';
}
if(l2 > 0) {
l2--;
tem = tem + num2.charAt(l2) - '0';
}
carry = tem/10;
result.append(tem%10);
}
return result.reverse().toString();
}