zoukankan      html  css  js  c++  java
  • 008字符串转换整数

    写在前面,参考的是力扣官网的解题思路,好懂和图解

    一、java代码

    /*
     * @lc app=leetcode.cn id=8 lang=java
     *
     * [8] 字符串转换整数 (atoi)
     */
    
    // @lc code=start
    class Solution {
        public int myAtoi(String str) {
    
            //字符串转换为数组
            char[] chars=str.toCharArray();
            //数组长度
            int n=chars.length;
            //数组下标
            int idx=0;
            //去掉前导空格
            while(idx<n&&chars[idx]==' '){
                idx++;
            }
            //如果去掉前导空格后就到末尾了,则直接返回0
            if(idx==n){
                return 0;
            }
            //negative标记负号
            boolean negative=false;
    
            //判断第一个非空字符
            //如果遇到负号则记录下状态
            if(chars[idx]=='-'){
                negative=true;
                idx++;
                //如果遇到正号,可以忽略
            }else if(chars[idx]=='+'){
                idx++;
                //其他符号,则直接返回0
            }else if(!Character.isDigit(chars[idx])){
                return 0;
            }
            //输出的数,先定义为0
            int ans=0;
    
            //Character.isDigit判断是否为数字
            while (idx<n&&Character.isDigit(chars[idx])){
    
                //将字符数字转换为数字'1'-'0'=1
                int digit=chars[idx]-'0';
    
                //也就是说会在某一步`ans*10+digit>Integer.MAX_VALUE`
                //`*10`和`+digit`都可能会越界,那么只要把这些都移到右边去就可以了
                if(ans>(Integer.MAX_VALUE-digit)/10){
                    return negative?Integer.MIN_VALUE:Integer.MAX_VALUE;
                }
                //最基本的基本
                ans=ans*10+digit;
                //下标自增
                idx++;
            }
            return negative?-ans:ans;
    
        }
    }
    // @lc code=end
    
    
    

    二、题解分析

    做题思路

    1、去掉前导空格

    2、处理正负号

    3、识别数字,注意越界的情况

    代码解释

      1、这道题如果只是简单的字符串转换整数的话,就是简单的ans=ans*10+digit

      2、但是这道题可能会超过integer的最大表示

      3、也就是说会在某一步ans*10+digit>Integer.MAX_VALUE

    • *10+digit都可能会越界,那么只要把这些都移到右边去就可以了

    • ans>(Integer.MAX_VALUE-digit)/10就是越界

  • 相关阅读:
    理解Cookie和Session的区别及使用
    数据库事务
    Mybatis和hibernate的优缺点比较
    MyBatis、JDBC相关知识
    JVM学习笔记(一,待整理)
    laravel运行url404错误
    电影TS、TC、SCR、R5、BD、HD等版本是什么意思
    mysql索引
    双系统更改启动顺序
    PHP Deprecated: Comments starting with '#' are deprecated in *.ini 警告解决办法
  • 原文地址:https://www.cnblogs.com/lxr-xiaorong/p/13451908.html
Copyright © 2011-2022 走看看