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;
    }
  • 相关阅读:
    Linux下C程序插入执行shell脚本
    #ifdef预编译相关用法
    LAMP开发之环境搭建(2014.12.7在ubuntu下)
    Qt在VS2010的安装与配置
    vs2010配备boost编程环境
    Ubuntu虚拟机与Window、Arm的通信
    大小端测试程序
    Ubuntu安装google Gtest
    设计模式之单例模式
    设计模式之原型模式
  • 原文地址:https://www.cnblogs.com/long3216/p/4438234.html
Copyright © 2011-2022 走看看