zoukankan      html  css  js  c++  java
  • [LeetCode] #8 String to Integer (atoi)

    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.

    题目不难,一样要注意int的边界问题。时间:19ms

    代码如下:

    class Solution {
    public:
        int atoi(string str) {
            if (str.size() == 0)
                return  0;
            bool sign = false;
            long long num = 0;
            string::const_iterator iter = str.begin();
            while (iter != str.end() && *iter == ' '){ ++iter; }
            if (iter == str.end())
                return 0;
            if (*iter == '+' || *iter == '-'){
                if (*iter == '-')
                    sign = true;
                iter++;
            }
            while (iter != str.end()){
                if (*iter >= '0'&&*iter <= '9'){
                    num = num * 10 + *iter - '0';
                    if (num > 2147483648){
                        num = 2147483648;
                        break;
                    }
                }
                else
                    break;
                ++iter;
            }
            if (sign == true)
                num = 0 - num;
            else if (num == 2147483648)
                num--;
            return num;
        }
    };
    “If you give someone a program, you will frustrate them for a day; if you teach them how to program, you will frustrate them for a lifetime.”
  • 相关阅读:
    java中如何高效的判断数组中是否包含某个元素---
    反射--
    Json----
    Ajax学习(1)
    Jdbc学习---
    java---内部类
    java中的多态
    spring是什么
    quartz的配置文件
    浅谈Job&JobDetail
  • 原文地址:https://www.cnblogs.com/Scorpio989/p/4413790.html
Copyright © 2011-2022 走看看