字符串转整数

题目描述

将一个字符串转换成一个整数,要求不能使用字符串转换整数的库函数。 数值为0或者字符串不是一个合法的数值则返回0

输入描述:
1
输入一个字符串,包括数字字母符号,可以为空
输出描述:
1
如果是合法的数值表达则返回该数字,否则返回0
输入例子:
1
2
+2147483647
1a33
输出例子:
1
2
2147483647
0

思路

将字符串转化为数组进行处理,例如12 = 110+2;123 = 12\10+3;

此外还需要注意一下几点

  1. 字符串是否为空
  2. 字符串两边有空格自动屏蔽
  3. 字符串是否溢出(大于最大值,小于最小值)
  4. 字符串的符号怎么判断
  5. “+123”和”123”效果一样
  6. 字符串的每一位的正确性

算法实现

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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
public class StringToInt {
public static void main(String[] args) {
String a = "12a3";
int b = StringToInt(a);
System.out.println(b);
}

public static int StringToInt(String str) {
if (str == null || str.equals("")) {
return 0;
}
String s = str.trim();
int result = 0;
int symbol = 1;//符号位
int i = 0, len = s.length();
char[] array = s.toCharArray();
boolean isValid = false;//结果是否有效
if (len > 0) {
char firstChar = s.charAt(0);
if (firstChar < '0') {
if (firstChar == '-') {
symbol = -1;
} else if (firstChar != '+') {
return 0;
}
if (len == 1){
return 0;
}
i++;
}
for (int j = i;j < len;j++){
if (!('0' <= array[j] && array[j] <= '9' )){
isValid = true;
return 0;
}
result = result*10 + array[j] - '0';
if ((symbol == 1 && result>Integer.MAX_VALUE)||(symbol == -1 && result < Integer.MIN_VALUE)){
isValid = true;
return 0;
}
}
}else {
return 0;
}
return result*symbol;

}
}
-------------本文结束感谢您的阅读-------------

本文标题:字符串转整数

文章作者:Cui Zhe

发布时间:2018年11月13日 - 23:11

最后更新:2018年11月14日 - 00:11

原始链接:https://cuizhe1023.github.io/2018/11/13/字符串转整数/

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。