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

xiaoxiao2021-02-28  8

解题思路:

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位如果是数字或者是+,—则继续遍历,否则直接返回false char 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') { // 证明包含非数字字符,直接跳出循环,返回false return true; } } } else { // 首位就包含除正负号外的非数字字符 return true; } return false; }

转载请注明原文地址: https://www.6miu.com/read-200174.html

最新回复(0)