剑指offer面试题49 把字符串转换成整数 (java实现)

来源:互联网 发布:攻城掠地烈焰战车数据 编辑:程序博客网 时间:2024/05/04 14:09

解题思路:

1.判断字符串输入是否合法,重点判断一个字符串除第一个字符外是否包含非数字字符,若包含,则返回0,不包含,则进行转换成整数操作;

2.取出字符串第一个字符,遍历第一个字符之后的所有字符,计算除第一个字符外的所有字符串组成的整数大小;

3.若第一个字符不是正负号,则加上第一个字符对应的数字大小。

public class Solution {public int StrToInt(String str) {if (str == null || str.length() == 0 || hasNonNumerical(str)) {// 如果字符串为空并且包含非数字字符return 0;}// 此时的字符串肯定是数字字符串// 因为返回值限定为int型,所以无需考虑大数问题char firstChar = str.charAt(0);// 先将除第一位的数字转换成整数int sumExcludeFirst = 0;int sum = 0;for (int i = 1; i < str.length(); i++) {// 拿出当前字符char c = str.charAt(i);// 将当前字符转换为整数int convert = c - '0';if (firstChar == '+' && sum <= Integer.MAX_VALUE) {sum += convert * Math.pow(10, str.length() - 1 - i);} if (firstChar == '-' && sum >= Integer.MIN_VALUE) {sum -= convert * Math.pow(10, str.length() - 1 - i);}if (firstChar >= '0' && firstChar <= '9' && sum <= Integer.MAX_VALUE) {sum += convert * Math.pow(10, str.length() - 1 - i);}}int first = firstChar - '0';if (firstChar >= '0' && firstChar <= '9') {sum += first * Math.pow(10, str.length() - 1);}if (sum > Integer.MAX_VALUE || sum < Integer.MIN_VALUE) {return 0;}return sum;}// 判断一个字符串除第一个字符外是否包含非数字字符,第一个字符可以是+或者是—private boolean hasNonNumerical(String str) {int length = str.length();// 取出第0位,若第0位如果是数字或者是+,—则继续遍历,否则直接返回falsechar c = str.charAt(0);if ((c >= '0' && c <= '9') || (c == '+') || (c == '-')) {// 有必要进行之后的遍历for (int i = 1; i < length; i++) {// 取出当前字符c = str.charAt(i);if (c < '0' || c > '9') {// 证明包含非数字字符,直接跳出循环,返回falsereturn true;}}} else {// 首位就包含除正负号外的非数字字符return true;}return false;}



阅读全文
0 0