【CT】LeetCode手撕—8. 字符串转换整数 (atoi)


题目


1- 思路

思路

  • x 的平方根 ——> 利用二分 ——> 二分的 check条件为 k^2 <= x

2- 实现

⭐8. 字符串转换整数 (atoi)——题解思路

在这里插入图片描述

class Solution {
    public int myAtoi(String s) {
        int res = 0;
        int len = s.length();
        int k = 0;
        
        // 1. 判空
        while(k<len && s.charAt(k) ==' ') k++;
        if(k==len) return 0;

        // 2.判断正负
        int minus = 1;
        if(s.charAt(k) == '-'){
            minus = -1;
            k++;
        }else if (s.charAt(k)=='+'){
            k++;
        }

        // 3. 判断越界
        while(k<len && s.charAt(k) >='0' && s.charAt(k)<='9'){
            int x = s.charAt(k)-'0';

            if(minus > 0 && res > (Integer.MAX_VALUE - x) / 10 ) return Integer.MAX_VALUE;
            if(minus < 0 && -res < (Integer.MIN_VALUE + x) / 10) return Integer.MIN_VALUE;

            res = res*10 + x;
            k++;
        }
        
        res = res*minus;
        return res;
    }
}

3- ACM 实现

public class myAtoi {


    public static int myAtoi(String s){
        int len = s.length();
        int k = 0;
        int res = 0;

        // 1. 判空
        while(k<len && s.charAt(k)==' ') k++;
        if(k==len) return 0;

        // 2. 判断 minus
        int minus = 1;
        if(s.charAt(k) == '-'){
            minus = -1;
            k++;
        }else{
            k++;
        }
        // 3. 判断是否越界
        while (k<len && s.charAt(k)>='0' && s.charAt(k)<='9'){
            int x = s.charAt(k)-'0';
            if(minus > 0 && res > (Integer.MAX_VALUE - x) / 10 ) return Integer.MAX_VALUE;
            if(minus < 0 && -res < (Integer.MIN_VALUE + x) / 10) return Integer.MIN_VALUE;

            res = res*10+x;
            k++;
        }
        res = res*minus;
        return res;
    }
    public static void main(String[] args) {
        System.out.println("输入你需要转换的字符串");
        Scanner sc = new Scanner(System.in);
        String input = sc.nextLine();
        System.out.println("结果是"+myAtoi(input));
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值