把字符串转换成整数
将一个字符串转换成一个整数,要求不能使用字符串转换整数的库函数。 数值为0或者字符串不是一个合法的数值则返回0
输入一个字符串,包括数字字母符号,可以为空,
如果是合法的数值表达则返回该数字,否则返回0
in:
+2147483647 1a33
out:
2147483647 0
public class Solution { public int StrToInt(String str) { if (str == null || str.equals("0") ||str.equals("")) return 0; boolean isPositive = true; if (str.charAt(0) == '+') { isPositive = true; str = str.substring(1); } else if (str.charAt(0) == '-') { isPositive = false; str = str.substring(1); } else { isPositive = true; } int ans = 0; int ary = 1; for (int i=str.length()-1; i>=0; i--) { if (!isDigit(str.charAt(i))) { return 0; } ans += ary * (str.charAt(i)-'0'); ary *= 10; } ans = isPositive ? ans : -ans; return ans; } public boolean isDigit(char ch) { if (ch < '0' || ch > '9') return false; return true; } }
作者:Pickle
声明:对于转载分享我是没有意见的,出于对博客园社区和作者的尊重一定要保留原文地址哈。
致读者:坚持写博客不容易,写高质量博客更难,我也在不断的学习和进步,希望和所有同路人一道用技术来改变生活。觉得有点用就点个赞哈。