zoukankan      html  css  js  c++  java
  • leetcode 8 String to Integer (atoi)

    没什么算法可言,但是就是要考虑周全。

    1.有可能ans超过long long那么溢出以后正负可能就不对了,所以先判断超过10位的话就直接输出边值。

    2.前一部分不符合规定就return 0,有这么几个情况都不行:+-2,- 992(负号和第一个数之前多了个空格,就不行)。但是+5455这种是对的。

    3.5545a55这种,a及其后面的都不能算。

    class Solution {
    public:
        int myAtoi(string str) {
            int len=str.length();
            string st;
            int fu=2;
            for(int i=0;i<len;i++){
                if(st.length()==0&&(!(str[i]>='0'&&str[i]<='9'))){
                    if(str[i]==' '&&fu==2){
                        continue;
                    }
                    else if(str[i]=='-'&&fu==2){
                        fu=1;
                    }
                    else if(str[i]=='+'&&fu==2){
                        fu=0;
                    }
                    else return 0;
                }
                else if(st.length()>0&&(!(str[i]>='0'&&str[i]<='9'))){
                    break;
                }
                else if(str[i]>='0'&&str[i]<='9'){
                    st+=str.substr(i,1);
                }
            }
            int ll=st.length();
            if(ll==0) return 0;
            long long int ans=0,shi=1;
            if(ll>10){
                if(fu==1)return -2147483648;
                else return 2147483647;
            }
            for(int i=ll-1;i>=0;i--){
                ans+=shi*(st[i]-'0');
                shi*=10;
            }
            if(fu==1) ans=-ans;
            if(ans>2147483647) return 2147483647;
            else if(ans<-2147483648) return -2147483648;
            else return (int)ans;
        }
    };
  • 相关阅读:
    sql注入的防护
    mysql及sql注入
    机器学习之新闻文本分类。
    python导入各种包的方法——2
    爬去搜狐新闻历史类
    前端展示
    热词分析前端设计
    爬虫经验总结二
    爬虫经验总结一
    SpringBoot配置Druid数据库连接池
  • 原文地址:https://www.cnblogs.com/zywscq/p/4912563.html
Copyright © 2011-2022 走看看