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;
        }
    };
  • 相关阅读:
    RocketMQ中Producer消息的发送源码分析
    VS等待调试
    Window&Linux遍历某一文件夹
    遍历当前USB设备信息
    批处理常用符号详解
    Windows 批处理(bat)语法大全
    Windows CMD命令大全(值得收藏)
    遍历文件夹
    ASCII,UTF-8,Unicode字符串相互转换
    shellexecute的使用和X64判断
  • 原文地址:https://www.cnblogs.com/shellfishsplace/p/5830014.html
Copyright © 2011-2022 走看看