• Leetcode -- Day 8


    Form today on, I changed to Math module question.

    Question 1

    String to Integer (atoi)

     Implement atoi to convert a string to an integer.
     
    Remember one thing here. The result is initialized as a double, as it will * 10 later, where if it is integer, it will exceed the max limit. So make it as double here. 
     
    public int myAtoi(String str) {
            if (str == null || str.length() == 0)
                return 0;
            str = str.trim();
            
            char flag = '+';
            int i = 0;
            if (str.charAt(0) == '-') {
                flag = '-';
                i++;
            } else if (str.charAt(0) == '+') {
                i++;
            }
                
            int result = 0;
            
            while (str.length() > i && str.charAt(i) >= '0' && str.charAt(i) <= '9') {
                result = result * 10 + (str.charAt(i) - '0');
                i++;
            }
            
            if (flag == '-')
            result = 0-result;
     
            // handle max and min
            if (result > Integer.MAX_VALUE)
                return Integer.MAX_VALUE;
         
            if (result < Integer.MIN_VALUE)
                return Integer.MIN_VALUE;
         
            return (int) result;
        }
  • 相关阅读:
    SPOJ 8093 JZPGYZ
    UVA1030 Image Is Everything
    UVA11996 Jewel Magic
    UVA11922 Permutation Transformer
    UVA1479 Graph and Queries
    P3224 [HNOI2012]永无乡
    UVA11020 Efficient Solutions
    UVA12206 Stammering Aliens
    UVA11107 Life Forms
    UVA11019 Matrix Matcher
  • 原文地址:https://www.cnblogs.com/timoBlog/p/4649836.html
Copyright © 2020-2023  润新知