zoukankan      html  css  js  c++  java
  • Leetcode: 8. String to Integer (atoi)

    Description

    Implement atoi to convert a string to an integer.

    Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases.

    Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front.

    思路

    • 这个题好像也没有什么简便方法,注意边界条件吧

    代码

    • 时间复杂度:O(n)
    class Solution {
    public:
        const int min_int = -2147483648;
        const int max_int = 2147483647;
        
        int myAtoi(string str) {
            int len = str.size();
            if(len == 0) return 0;
            
            int i = 0;
            while(i < len && str[i] == ' ') i++;
            
            bool isSymbol = false;
            bool isNegative = false;
            if(i < len && str[i] == '-'){
                isSymbol = true;
                isNegative = true;
                i++;
            }
            
            if(!isSymbol && str[i] == '+'){
                isSymbol = true;
                i++;
            }
          
            if(i < len && str[i] >= '0' && str[i] <= '9'){
                long long sum = 0;
                while(i < len && str[i] >= '0' && str[i] <= '9'){
                   sum = sum * 10 + (str[i] - '0');
                    if(sum > max_int){
                        if(isNegative) return min_int;
                        return max_int;
                    }
                    i++;
                }
    
                return isNegative ? -sum : sum;
            }
            else return 0;
        }
    };
    
  • 相关阅读:
    Asp.net如何连接SQL Server2000数据库
    是男人,都可以看看这个
    体验Flash MX(8):控制时钟Timer
    好代码
    sql 大数据量插入优化
    Xcode 真机程序发布测试
    Xcode 真机程序发布测试
    用git备份代码
    sql 大数据量插入优化
    UIView学习笔记
  • 原文地址:https://www.cnblogs.com/lengender-12/p/6810152.html
Copyright © 2011-2022 走看看