AcWing
  • 首页
  • 题库
  • 题解
  • 分享
  • 问答
  • 活动
  • 应用
  • 吐槽
  • 登录/注册

AcWing 87. 把字符串转换成整数-java    原题链接    中等

作者: 作者的头像   @zengjx ,  2020-03-11 22:23:23 ,  阅读 187


-1


class Solution {
public int strToInt(String str) {

    if(str==null || str.length()==0){
        return 0;
    }
    long num=0;
    int count=1;
    char[] ch =str.toCharArray();


    for(int i=ch.length-1;i>=0;i--){
        //空格
        if(ch[i]==' '){
            continue ;
        }
        //正负数
     if(ch[i]=='-'){

        num=-1*num;
       // System.out.println("fushu");
    }
      //整数前面有字母la123


      if(i+1<ch.length){
      if(ch[i+1] >='0'  && ch[i+1]<='9'  ){


       if((ch[i]>='A'&& ch[i]<='Z') || (ch[i]>='a'  && ch[i]<='z')){

           return 0;
       }
      }
      }
      //整数后面是字母 123la
      if(i-1  >0){
      if(ch[i-1]<='0' && ch[i-1]>='9'){

          if((ch[i]>='A'&& ch[i]<='Z') || (ch[i]>='a'  && ch[i]<='z')){

           return 0;
       }

       }
      }

       if(ch[i]>='0' && ch[i]<='9'){
           // System.out.println(ch[i]);
           num+=(ch[i]-'0')*count;
           // System.out.println("num ="+num);
           count=count*10;
       }


    }

    if(num>Integer.MAX_VALUE ){

       return Integer.MAX_VALUE;
    }
    if(num<Integer.MIN_VALUE){
        return Integer.MIN_VALUE;
    }

    return (int)num;

}
}

0 评论

你确定删除吗?

© 2018-2021 AcWing 版权所有  |  京ICP备17053197号-1
联系我们  |  常见问题
AcWing
请输入登录信息
更多登录方式: 微信图标 qq图标
请输入绑定的邮箱地址
请输入注册信息