• 【LeetCode】12.String to Integer (atoi)


    比较简单的题目,但是还是提交了好几遍才A掉一一!

    需要考虑的:

    (1)字符串前面的空格 trim()或者while()

    (2)正负符号

    (3)只取最前面的数字字符,一旦出现非数字字符后面即使有数字也不考虑了

    (4)空字符串 

    (5)溢出:最大数最小数两种

          遗忘了一种情况 ,出现了下面的错误。解决方法是:

    加上|| (sum>=1000000000)

    Submission Result: Wrong Answer

    Input: " -11919730356x"
    Output: 965171532
    Expected: -2147483648

    正确代码如下:

    public class Solution {
        public int atoi(String str) {
            // Note: The Solution object is instantiated only once and is reused by each test case.
           
            int sum=0,temp=0;
            int i=0;
            boolean negtive=false;
            boolean over=false;
            final int INT_MAX=2147483647;
            final int INT_MIN=-2147483648;
            str=str.trim();
         //while (i < str.length() && str.charAt(i) == ' ') i++; if(str.length()==0) return 0; if(str.charAt(i)=='-'){ negtive=true; i++; } if(str.charAt(i)=='+'){ i++; } while(i<str.length() && str.charAt(i) >= '0' && str.charAt(i) <= '9'){ temp = str.charAt(i)-'0'; if (sum >= 214748364) { if ((!negtive && temp>=7) || negtive && temp>=8 || (sum>=1000000000)) { over = true; break; } } sum=sum*10+temp; i++; } if(over==true && negtive==true) return INT_MIN; if(over==true && negtive==false) return INT_MAX; if(negtive) return -1*sum; else return sum; } }
  • 相关阅读:
    网站测试
    shell102输出数组
    shell101变量
    shell100for无参数形式
    shell99函数中传数组
    shell98函数的参数
    将php中session存入redis中
    windows下安装redis客户端
    window下phpstudy开启redis扩展
    *ginx下开启phpredis扩展
  • 原文地址:https://www.cnblogs.com/guozhiguoli/p/3371100.html
Copyright © 2020-2023  润新知