7.13 第一次做,不能 AC
7.14 不能 AC
7.15 差了一点,过吧!

题目描述


原题链接:https://leetcode-cn.com/problems/ba-zi-fu-chuan-zhuan-huan-cheng-zheng-shu-lcof/

解题思路


K 神题解:https://leetcode-cn.com/problems/ba-zi-fu-chuan-zhuan-huan-cheng-zheng-shu-lcof/solution/

  • 数字字符转换成数字要记得减去字符 ‘0’
  1. class Solution {
  2. public int strToInt(String str) {
  3. char[] c = str.trim().toCharArray();
  4. if(c.length == 0) return 0;
  5. int boundary = Integer.MAX_VALUE / 10, res = 0;
  6. int sign = 1, i = 1;
  7. if(c[0] == '-') sign = -1;
  8. else if(c[0] != '+') i = 0;
  9. for(int j = i; j < c.length; j++) {
  10. if(c[j] < '0' || c[j] > '9') break;
  11. if(res > boundary || res == boundary && c[j] > '7') return sign == 1 ? Integer.MAX_VALUE : Integer.MIN_VALUE;
  12. res = res * 10 + (c[j] - '0');
  13. }
  14. return sign * res;
  15. }
  16. }