{面试题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;
}

 

posted @ 2015-04-18 22:38  long#long  阅读(355)  评论(0编辑  收藏  举报