zoukankan      html  css  js  c++  java
  • {面试题49} 把字符串转换成整数

    From 剑指Offer 何海涛 著

    #include <iostream>
    #include <string>
    #include <cctype> bool g_valid = false; int StrToInt(const std::string& s) { long long res = 0ll; int n = s.size(); int i= 0; g_valid = true; while(i<n && s[i] == ' ') { i++; } bool isNegative = false; if(s[i] == '-') { isNegative = true; i++; } else if(s[i] == '+') { i++; } if(i== n) { g_valid = false; return res; } while(i<n && isdigit(s[i])) { res *= 10; res += s[i] - '0'; i++; if(!isNegative && res > (long)0x7fffffff || isNegative&& -res < (long)0x80000000) { g_valid = false; return 0; } } if(i< n) { g_valid = false; return 0; } return isNegative ? -res : res; }

    测试集:

    void test(const std::string &s, int n, bool valid) {
        std::cout << std::boolalpha<< (StrToInt(s) == n && valid == g_valid) << std::endl;
    }
    
    int main(int argc, char* argv[]) {
    
        test("", 0, false);
        test("  ", 0, false);
        
        test("+", 0, false);
        test("-", 0, false);
    
        test("123", 123, true);
        test("+0", 0, true);
        test("-0", 0, true);
        test("+123", 123, true);
        test("-123", -123, true);
        
        test("abc", 0, false);
        test("1a33", 0, false);
        
        //有效的最大正整数, 0x7FFFFFFF
        test("+2147483647", 2147483647, true);
        test("+2147483648", 0, false);
        
        //有效的最小负整数, 0x80000000
        test("-2147483648", -2147483648, true);
        test("-2147483649", 0, false);
    
        return 0;
    }
  • 相关阅读:
    js 运算符优先级
    原生js获取样式
    RGBA 与opacity
    闭包(自己的学习+理解~~水水的)
    css 单位-px、em、rem、百分比
    js之正则1
    querySelector和querySelectorAll
    关于瀑布流的算法(转淘宝ued)
    瀑布流的几个注意点
    jsonp跨域
  • 原文地址:https://www.cnblogs.com/long3216/p/4438234.html
Copyright © 2011-2022 走看看