zoukankan      html  css  js  c++  java
  • 剑指 Offer 67. 把字符串转换成整数

    class Solution {
        public int strToInt(String str) {
            int res =0;
            //用于数字溢出判断
            int bndry = Integer.MAX_VALUE / 10;
            //sign标记 正负号
            int i = 0, sign = 1,length = str.length();
            //边界判断
            if(length == 0) return 0;
            //去掉空格
            while(str.charAt(i) == ' ')
                if(++i == length) return 0;
            //第一个字符 是‘-’, sign标记为 -1
            if(str.charAt(i) == '-') sign = -1;
            //如果第一位是符号,移到下一位开始
            if(str.charAt(i) == '-' || str.charAt(i) == '+') i++;
            for(int j = i; j < length; j++){
                //字符 不在 0~9,表示不是数字,直接返回
                if(str.charAt(j) < '0' || str.charAt(j) > '9') break;
                //判断溢出
                if(res > bndry || res == bndry && str.charAt(j) > '7')
                    return sign == 1 ? Integer.MAX_VALUE : Integer.MIN_VALUE;
                //拼接字符
                res = res * 10 + (str.charAt(j) - '0');
            }
            return sign * res;
        }
    }
  • 相关阅读:
    AddParent
    AddChild
    贝塞尔曲线代码
    顶点纹理shader
    抽象方法与抽象类
    Application类
    布局组件
    C#单例和Unity单例
    Unity&UGUI
    Json解析
  • 原文地址:https://www.cnblogs.com/peanut-zh/p/14152996.html
Copyright © 2011-2022 走看看