zoukankan      html  css  js  c++  java
  • LeetCode String To Integer

    Consider very carefully to cover all the possible input conditions!

    atoi: string -> integer

    input: str

    1. size:

      different C++ data type's size in different machine [list]: http://hi.baidu.com/yangyangye2008/item/ba0a35395420d2f9df222157

      (default: int - 4 bytes)

    2. begin (' ','+','-') , others' error

    3. inside('0'-'9', ' '), others' error

    4. attention to the return type: int

      but set the string-num type "long long" first, then judge it.

     * if string-num's size is bigger than the int-type size, then return the biggest int(positive/negtive):

      if(negtive)
      {
        ret = ret<=0x80000000 ? ~(unsigned int)ret+1 : 0x80000000;
      }
      else
      {
        ret = ret<=0x7FFFFFFF ? ret : 0x7FFFFFFF;
      }

    5. integer:     aN = ((((a1*10+a2)*10+...)*10...)+an-1)*10+an;

    attach code:

    class Solution {
    public:
        int atoi(const char *str) {
            // Start typing your C/C++ solution below
            // DO NOT write int main() function
            
            long long ret = 0;
            int i = 0;
            bool negtive = false;
            
            while(str[i] == ' ') i++;
            
            if(str[i]=='+') i++;
            else if(str[i]=='-') {negtive=true;i++;}
            
            while(str[i]!='\0' && str[i]>='0' && str[i]<='9')
            {
                int d = str[i]-'0';
                ret = 10*ret+d;
                i++;
            }
            
            if(negtive)
            {
                ret = ret<=0x80000000 ? ~(unsigned int)ret+1 : 0x80000000;        
             }
             else
             {
                ret = ret<=0x7FFFFFFF ? ret : 0x7FFFFFFF;
             }
            
            return ret;
            
        }
    };
  • 相关阅读:
    Linux下安装启动nginx的过程
    shell编程
    Linux中的权限管理
    Linux中的模式转换
    Linux入门2
    Linux入门1
    数据库的多表查询及左右连接
    Python命令行参数sys.argv[]
    Python 读取csv文件到excel
    高级技巧
  • 原文地址:https://www.cnblogs.com/CathyGao/p/3019306.html
Copyright © 2011-2022 走看看