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

相关推荐
苏言の狗15 分钟前
小R的并集大小期望计算 | 蛮力
数据结构·算法
BineHello22 分钟前
MPC用优化求解器 - 解决无人机轨迹跟踪
算法·矩阵·自动驾驶·动态规划·无人机
誓约酱24 分钟前
(每日一题) 力扣 14 最长公共前缀
算法·leetcode·职场和发展
用户611881615196229 分钟前
Java基础面试题
java
DavidSoCool1 小时前
Elasticsearch Java API Client [8.17] 使用
java·大数据·elasticsearch
无世世1 小时前
【Java从入门到起飞】面向对象编程(高级)
java·开发语言
Vic101011 小时前
Mac如何查看 IDEA 的日志文件
java·macos·intellij-idea
陈逸轩*^_^*1 小时前
idea打不开,idea打不开,Error occurred during initialization of VM
java·ide·intellij-idea
冠位观测者1 小时前
【Leetcode 每日一题 - 补卡】2070. 每一个查询的最大美丽值
数据结构·算法·leetcode
=PNZ=BeijingL1 小时前
使用Mockito实现单元测试
java