zoukankan      html  css  js  c++  java
  • 08.字符串转换位整数

    题目:

     

     提交:

    class Solution {
        public int myAtoi(String str) {
             str = str.trim();
            if (str == null || str.length() == 0) return 0;
    
            // + - 号
            char firstChar = str.charAt(0);
            int sign = 1;
            int start = 0;
            long res = 0;
            if (firstChar == '+') {
                sign = 1;
                start++;
            } else if (firstChar == '-') {
                sign = -1;
                start++;
            }
    
            for (int i = start; i < str.length(); i++) {
                if (!Character.isDigit(str.charAt(i))) {
                    return (int) res * sign;
                }
                res = res * 10 + str.charAt(i) - '0';
                if (sign == 1 && res > Integer.MAX_VALUE) return Integer.MAX_VALUE;
                if (sign == -1 && res > Integer.MAX_VALUE) return Integer.MIN_VALUE;
            }
            return (int) res * sign;
        }
    }

    评论:奇葩输入太多,只能参考别人的代码

  • 相关阅读:
    s
    qq
    qqq
    q
    qq
    http请求报文
    qq
    q
    qqq
    java对象-String的用法
  • 原文地址:https://www.cnblogs.com/bytecodebuffer/p/11442174.html
Copyright © 2011-2022 走看看