【剑指 Offer 题解】67. 把字符串转换成整数

题目描述

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

输入输出示例

Iuput:
+2147483647
1a33

Output:
2147483647
0

思路

public int strToInt(String str) {
   	if (str == null || "".equals(str)) {
   		return 0;
   	}
   	boolean isNegative = str.charAt(0) == '-';
   	int result = 0;
   	for (int i = 0; i < str.length(); i++) {
   		char ch = str.charAt(i);
   		if (i == 0 && (ch == '+' || ch == '-')) { /* 符号判断 */
   			continue;
   		}
   		if (ch < '0' && ch > '9') { /* 非法字符判断 */
   			return 0;
   		}
   		result = 10 * result + (ch - '0');
   	}
   	return isNegative ? -result : result;
   }
发布了18 篇原创文章 · 获赞 0 · 访问量 514

猜你喜欢

转载自blog.csdn.net/qingqingxiangyang/article/details/104245998