zoukankan      html  css  js  c++  java
  • [剑指offer] 49. 把字符串转换成整数

    题目描述

    将一个字符串转换成一个整数(实现Integer.valueOf(string)的功能,但是string不符合数字要求时返回0),要求不能使用字符串转换整数的库函数。 数值为0或者字符串不是一个合法的数值则返回0。

    输入描述:

    输入一个字符串,包括数字字母符号,可以为空

    输出描述:

    如果是合法的数值表达则返回该数字,否则返回0
    示例1

    输入

    +2147483647
        1a33

    输出

    2147483647
        0
    class Solution
    {
      public:
        int StrToInt(string str)
        {
            if (str == "")
                return 0;
            int s = 1;
            int curInd = 0;
            if (str[curInd] == '-')
            {
                s = -1;
                curInd++;
            }
            else if (str[curInd] == '+')
            {
                s = 1;
                curInd++;
            }
            int sum = 0;
            for (; curInd < str.length(); curInd++)
            {
                if (str[curInd] < 48 || str[curInd] > 57)
                    return 0;
                sum = sum * 10 + str[curInd] - 48;
            }
            return sum * s;
        }
    };
  • 相关阅读:
    node03
    node02
    node01
    Vue-router重修02
    Vue-router重修01
    Vue重修02
    VUE重修01
    利用表达式目录树进行实体映射
    C#托管堆和垃圾回收
    C# 异步锁
  • 原文地址:https://www.cnblogs.com/ruoh3kou/p/10182539.html
Copyright © 2011-2022 走看看