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

相关推荐
漂流瓶jz几秒前
UVA-11846 找座位 题解答案代码 算法竞赛入门经典第二版
数据结构·算法·排序算法·深度优先·aoapc·算法竞赛入门经典·uva
AlunYegeer29 分钟前
MyBatis 传参核心:#{ } 与 ${ } 区别详解(避坑+面试重点)
java·mybatis
米粒137 分钟前
力扣算法刷题 Day 31 (贪心总结)
算法·leetcode·职场和发展
少许极端41 分钟前
算法奇妙屋(四十)-贪心算法学习之路7
java·学习·算法·贪心算法
危笑ioi42 分钟前
helm部署skywalking链路追踪 java
java·开发语言·skywalking
夕除1 小时前
Mysql--15
java·数据库·mysql
smileNicky1 小时前
Linux 系列从多节点的catalina 日志中统计设备调用频次
java·linux·服务器
AlenTech1 小时前
647. 回文子串 - 力扣(LeetCode)
算法·leetcode·职场和发展
py有趣1 小时前
力扣热门100题之合并两个有序链表
算法·leetcode·链表
赵丙双1 小时前
spring boot 排除自动配置类的方式和原理
java·spring boot·自动配置