【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));
    }
}

相关推荐
聪明的笨猪猪24 分钟前
Java 工程案例:AI 生成 @Async 异步线程池踩坑
java·经验分享·面试·ai编程
学长毕设40 分钟前
基于SpringBoot公务员考试交流平台-附源码
java·spring boot·后端
好悬给我拽开线2 小时前
ZILOT 论文解析
算法
SL_staff3 小时前
私有化低代码:面向强监管行业的可控数字化实践
java·低代码
饮水桶_T3 小时前
JAVA IO流笔记
开发语言·数据结构·算法
三翼鸟数字化技术团队4 小时前
高性能存储引擎RocksDB:原理与Java生态实践
java
SL_staff4 小时前
JVS-APS有限产能建模的七个刚性支点:面向产线真实约束的技术实现解析
java·开源·全栈
特立独行的猫A4 小时前
少 3 个环节、少 1 次 ABI、少 3500 行代码:cj-tauri 与 Ionic/Capacitor 的鸿蒙桥接机制对比
java·后端·python
星夜离尘564 小时前
MATLAB 离散数据分箱:半开区间、末端点与计数、加权和、平均
算法·matlab
Pniubi4 小时前
力扣76.最小覆盖子串
算法·leetcode·职场和发展