zoukankan      html  css  js  c++  java
  • leetcode 8

    string类型转换为int类型,需要考虑不同的转换情况。

    “   04”  转换结果   4;

    “   4   43”  转换结果  4;

    “a@12 ”   转换结果    0;

    “12a”    转换结果    12;

    “ +12”   转换结果    12;

    “ +  12”  转换结果   0;

    “ -12”   转换结果     -12;

    “  -  12”  转换结果    0;

    “ +-12”   转换结果   0;

    其次就是对边界的考虑,若转换之后的数越上界,则返回上界;若转换之后的数越下界,则返回下界。

    代码如下:

    class Solution {
    public:
        int myAtoi(string str) {
            int result = 0;
            bool sign = true;
            int tag = 0;
            for(int i = 0; i < str.length(); ++i)
            {
                if(str[i] ==  ' ' && tag == 0)
                {
                    continue;
                }
                if(str[i] == '+' && tag == 0)
                {
                    tag = 1;
                    continue;
                }
                if(str[i] == '-' && tag == 0)
                {
                    tag = 1;
                    sign = false;
                    continue;
                }
                while(i < str.length())
                {
                    if((str[i] - '0') < 0 || (str[i] - '9') > 9)
                    {
                        return sign? result : -result; 
                    }
                    if(result > INT_MAX / 10)
                    {
                        return  sign? INT_MAX : INT_MIN;
                    }
                    result *= 10;
                    if ((str[i] - '0') > (INT_MAX - result))  
                        return sign? INT_MAX : INT_MIN;
                    result = result + str[i] - '0';
                    i ++;
                }
            }
            return sign? result : -result;
        }
    };
  • 相关阅读:
    Java中的逆变与协变
    JAVA中使用DOM解析XML文件
    ReentrantLock的使用
    tomcat源码 Container
    tomcat源码 Connector
    tomcat源码 StandardService
    BlockingQueue队列
    tomcat源码 StandardServer
    tomcat源码 分析 Catalina
    tomcat整体架构
  • 原文地址:https://www.cnblogs.com/shellfishsplace/p/5830014.html
Copyright © 2011-2022 走看看