数字与字符串
# 8. 字符串转换整数 (atoi) (opens new window)
class Solution {
public int myAtoi(String s) {
int n = s.length();
long ret = 0;
int i=0,sign=1;
// 去掉空格
while(i<n&&s.charAt(i)==' ')
i++;
if(i==n)
return 0;
if(s.charAt(i)=='-'){
sign = -1;
i++;
}else if(s.charAt(i)=='+'){
i++;
}
while(i<n&&s.charAt(i)>='0'&&s.charAt(i)<='9'){
ret = ret*10+s.charAt(i)-'0';
if(ret>Integer.MAX_VALUE)
break;
i++;
}
if((int)ret!=ret){
return sign==1?Integer.MAX_VALUE:Integer.MIN_VALUE;
}
return (int)ret*sign;
}
}
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
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
# 415. 字符串相加 (opens new window)
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){
int x = i>=0?num1.charAt(i)-'0':0;
int y = j>=0?num2.charAt(j)-'0':0;
int sum = x+y+carry;
carry = sum/10;
sum %= 10;
sb.append(sum);
i--;j--;
}
if(carry==1){
sb.append(1);
}
return sb.reverse().toString();
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21