各种反转-合集

各种反转-合集

(本系列是针对Leetcode上常见的反转进行总结。)

1. Leetcode 007 整数反转

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
public int reverse(int x) {
// 反转后的结果
int ans = 0;

while (x != 0){
// 拿到每一个个位
int pop = x % 10;

// 溢出处理
// ans * 10 + pop > Integer.MAXVAlUE
// ans * 10 + pop < Integer.MINVALUE
if ((ans > Integer.MAX_VALUE/10)
|| (ans == Integer.MAX_VALUE/10) && pop > 7){
return 0;
}

if ((ans < Integer.MIN_VALUE/10)
|| (ans == Integer.MIN_VALUE/10) && pop < -8){
return 0;
}

ans = ans * 10 + pop;
x /= 10;
}
return ans;
}

2. Leetcode 415. 字符串相加

给定两个字符串形式的非负整数 num1 和num2 ,计算它们的和。

提示:

1
2
3
num1 和num2 的长度都小于 5100
num1 和num2 都只包含数字 0-9
num1 和num2 都不包含任何前导零

你不能使用任何內建 BigInteger 库, 也不能直接将输入的字符串转换为整数形式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
class Solution {
public String addStrings(String num1, String num2) {
StringBuilder sb = new StringBuilder("");
// 初始化
int i = num1.length() - 1;
int j = num2.length() - 1;
int carry = 0;

while (i >= 0 || j >= 0){
// 对溢出进行处理,超过就补一个0
int n1 = i >= 0 ? num1.charAt(i) - '0':0;
int n2 = j >= 0 ? num2.charAt(j) - '0':0;
// 计算总和
int tmp = n1 + n2 + carry;
// 计算进位
carry = tmp / 10;
// 拿个位结果
sb.append(tmp % 10);
// 继续向前遍历
i--;
j--;
}

// 遍历完如果有进位再加一个1
if (carry == 1){
sb.append(1);
}

// 将StringBuilder转为字符串
return sb.reverse().toString();
}
}
打赏
  • 版权声明: 本博客所有文章除特别声明外,均采用 Apache License 2.0 许可协议。转载请注明出处!
  • © 2019-2022 Zhuuu
  • PV: UV:

请我喝杯咖啡吧~

支付宝
微信