• String to Integer


    String to Integer

    问题:

    Implement atoi to convert a string to an integer.

    Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases.

    Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front.

    思路:

      只是需要考虑的corner case多一些,思路很简单

    我的代码:

    public class Solution {
        public int myAtoi(String str) {
            if(str==null || str.length()==0 || str.trim().length()==0)  return 0;
            str = str.trim();
            boolean isPlus = true;
            if(str.charAt(0) == '-')
            {
                isPlus = false;
                str = str.substring(1);
            }
            else
            {
                if(str.charAt(0) == '+')
                    str = str.substring(1);
            }
            long rst = 0;
            for(int i=0; i<str.length(); i++)
            {
                char c = str.charAt(i);
                if(isValidNum(c))
                {
                    rst = rst*10 + (c-'0');
                    long tmp = (isPlus ? rst : rst*-1);
                    if(tmp>Integer.MAX_VALUE)   return Integer.MAX_VALUE;
                    if(tmp<Integer.MIN_VALUE)   return Integer.MIN_VALUE;
                }
                else 
                    break;
            }
            rst = (isPlus ? rst : rst*-1);
            return (int)rst;
        }
        public boolean isValidNum(char c)
        {
            return c<='9' && c>='0' ? true : false; 
        }
    
    }
    View Code
  • 相关阅读:
    后端——BA与图优化
    非线性优化
    后端卡尔曼滤波
    用HBuilderX把vue项目打包成apk
    vue中引入外部字体并使用
    使用iOS APP .mobileconfig套壳生成iosapp
    SCA组件识别
    赛事纪录 NOI 2022 统一省选
    Solution 「keyence2019_e 」Connecting Cities
    Open Cup 资源整理
  • 原文地址:https://www.cnblogs.com/sunshisonghit/p/4462148.html
Copyright © 2020-2023  润新知