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

目录

  • 题目
  • [1- 思路](#1- 思路)
  • [2- 实现](#2- 实现)
    • [⭐8. 字符串转换整数 (atoi)------题解思路](#⭐8. 字符串转换整数 (atoi)——题解思路)
  • [3- ACM 实现](#3- ACM 实现)

题目


1- 思路

思路

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

2- 实现

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

java 复制代码
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 实现

java 复制代码
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));
    }
}

相关推荐
用户83071968408230 分钟前
Spring Boot WebClient性能比RestTemplate高?看完秒懂!
java·spring boot
木心月转码ing2 小时前
Hot100-Day24-T128最长连续序列
算法
Assby2 小时前
从洋葱模型看Java与Go的设计哲学:为什么它们如此不同?
java·后端·架构
小肥柴2 小时前
A2UI:面向 Agent 的声明式 UI 协议(三):相关概念和技术架构
算法
belhomme4 小时前
(面试题)Netty 线程模型
java·面试·netty
学高数就犯困5 小时前
性能优化:LRU缓存(清晰易懂带图解)
算法
xlp666hub7 小时前
Leetcode第七题:用C++解决接雨水问题
c++·leetcode
CoovallyAIHub8 小时前
CVPR 2026 | MixerCSeg:仅2.05 GFLOPs刷新四大裂缝分割基准!解耦Mamba隐式注意力,CNN+Transformer+Mamba三
深度学习·算法·计算机视觉
NE_STOP8 小时前
MyBatis-plus进阶之映射与条件构造器
java