zoukankan      html  css  js  c++  java
  • Leet Code 8.字符串转换整数

    实现一个atoi函数,使其能将字符串转成整数,根据需要丢弃无用的开头空格字符,直到寻找到第一个非空格的字符为止。当我们寻找到的第一个非空字符为正或负号时,则将该符号与后面尽可能多的连续数字组合起来,作为该整数的正负号。之后可能有多余字符,可以被忽略。不能有效转换,返回0.

    题解

    没有什么优解,只能根据示例和题意不断做判断。先清除空格,后判断数字,最后小心数字溢出。

    我的解法代码
    public class Solution {
    
        public int myAtoi(String str) {
            int len = str.length();
    
            // 去除前导空格
            int index = 0;
            while (index < len) {
                if (str.charAt(index) != ' ') {
                    break;
                }
                index++;
            }
    
            if (index == len) {
                return 0;
            }
    
            // 第 1 个字符如果是符号,判断合法性,并记录正负
            int sign = 1;
            char firstChar = str.charAt(index);
            if (firstChar == '+') {
                index++;
                sign = 1;
            } else if (firstChar == '-') {
                index++;
                sign = -1;
            }
    
            // 不能使用 long 类型,这是题目说的
            int res = 0;
            while (index < len) {
                char currChar = str.charAt(index);
                // 判断合法性
                if (currChar > '9' || currChar < '0') {
                    break;
                }
    
                // 题目中说:环境只能存储 32 位大小的有符号整数,因此,需要提前判断乘以 10 以后是否越界
                if (res > Integer.MAX_VALUE / 10 || (res == Integer.MAX_VALUE / 10 && (currChar - '0') > Integer.MAX_VALUE % 10)) {
                    return Integer.MAX_VALUE;
                }
                if (res < Integer.MIN_VALUE / 10 || (res == Integer.MIN_VALUE / 10 && (currChar - '0') > -(Integer.MIN_VALUE % 10))) {
                    return Integer.MIN_VALUE;
                }
    
                // 每一步都把符号位乘进去
                res = res * 10 + sign * (currChar - '0');
                index++;
            }
    
            return res;
        }
    }
    
  • 相关阅读:
    PowerDesigner中利用数据库表反向生成PDM(jdk必须是32位)
    Struts2 Web Project 实现中文、英语的切换
    一张图解决Struts2添加源码
    Struts2配置文件struts.xml的编辑自动提示代码功能
    Hibernate多对一(注解)
    SQL Server 日期和时间函数
    ORACLE日期时间函数大全
    ORACLE中函数MONTHS_BETWEEN的使用
    SQL经典面试题及答案
    SQL数据库面试题以及答案
  • 原文地址:https://www.cnblogs.com/chenshaowei/p/12374628.html
Copyright © 2011-2022 走看看