Leetcode记录 8字符串转换整数

在这里插入图片描述
思路:先判断是否有±号,再取整数的第一个下标i,再取最后一个下标j,用str.substring(i,j)得到数字字符串,用num记录数值,遍历数字字符串,将当前数字加入num中,num=num10+cur(num=num10-cur),判断加入当前数字会不会超过最大值用num>=Integer.MAX_VALUE/10 &&cur>7,判断是否会超过最小值用num<=Integer.MIN_VALUE &&cur>8.

class Solution {
    public int myAtoi(String str) {
        int len=str.length();
        boolean negative=false;
        int i;
        for(i=0;i<len;i++){
            if(str.charAt(i)>='0' && str.charAt(i)<='9'){
                break;
            }
            else if(str.charAt(i)=='+'){
                negative=false;
                i++;
                break;
                
            }
            else if(str.charAt(i)=='-'){
                negative=true;
                i++;
                break;
            }
            else if(str.charAt(i)==' '){
                 continue;
            }
            else{
                return 0;
            }
        }
        int j;
        for(j=i;j<len;j++){
            if(str.charAt(j)>='0' && str.charAt(j)<='9'){
                continue;
            }
            else{
                break;
            }
        }
        
        String numstr=str.substring(i,j);
        System.out.println(numstr);
        int num=0;
        for(int k=0;k<numstr.length();k++){
            int cur=numstr.charAt(k)-'0';
            if(negative){
                if( num < Integer.MIN_VALUE/10 || num==Integer.MIN_VALUE/10 && cur>8 ){
                    return Integer.MIN_VALUE;
                }
                num=num*10-cur;
            }
            else{
                if( num > Integer.MAX_VALUE/10 || num==Integer.MAX_VALUE/10  &&  cur>7 ){
                    return Integer.MAX_VALUE;
                }
                num=num*10+cur;
            }
        }
        return num;
        
        
        
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值