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

相关推荐

  1. leetCode算法—8. 字符串转换整数 (atoi)

    2024-07-11 14:48:06       69 阅读
  2. Leetcode 8. 字符串转换整数 (atoi)

    2024-07-11 14:48:06       30 阅读
  3. C++atoi函数字符串转换成数字

    2024-07-11 14:48:06       53 阅读
  4. PTA 7-238 整数转换字符串

    2024-07-11 14:48:06       57 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-07-11 14:48:06       67 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-07-11 14:48:06       72 阅读
  3. 在Django里面运行非项目文件

    2024-07-11 14:48:06       58 阅读
  4. Python语言-面向对象

    2024-07-11 14:48:06       69 阅读

热门阅读

  1. ThingsBoard本地windows环境启动

    2024-07-11 14:48:06       26 阅读
  2. Oracle各种连接写法介绍

    2024-07-11 14:48:06       24 阅读
  3. C# 委托和事件

    2024-07-11 14:48:06       20 阅读
  4. MySQL常见的几种索引类型及对应的应用场景

    2024-07-11 14:48:06       25 阅读
  5. 带内管理与带外管理

    2024-07-11 14:48:06       21 阅读
  6. linux 内核 红黑树接口说明

    2024-07-11 14:48:06       20 阅读