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;
        }
    }
    
  • 相关阅读:
    MVC Web Api 发布到Azure报错
    WCF Rest post请求
    CRM2011部署问题小结
    CRM 2011 开发中遇到的问题小结
    SQL Server 2012 从备份中还原数据库
    Spring注解@Resource和@Autowired区别对比(转)
    synchronized 锁的是方法还是对象还是类?测试实例
    Java经典死锁范例
    java的单例模式,为什么需要volatile(转)
    Windows自动上传,并执行Linux指定shell文件
  • 原文地址:https://www.cnblogs.com/chenshaowei/p/12374628.html
Copyright © 2011-2022 走看看