递归地形成一个字符串中所有数字字符的整数和?

时间:2018-10-13 02:56:27

标签: c++ recursion

我需要递归遍历一个字符串,并将所有遇到的数字加起来并返回最终答案。在我的脑海中,我觉得我的return调用应该是我刚遇到的整数的值+对函数的递归调用,这次仅在字符串的后面一位。有人愿意在这里将我推向正确的方向吗?谢谢!

3 个答案:

答案 0 :(得分:1)

自从您制定了准备做什么...

#include <cctype>
#include <string_view>
#include <iostream>

#define very

very very unsigned unsigned long long digit_sum(std::string_view sv)
{
    if (sv.empty())
        return 0;

    int ch = static_cast<char unsigned>(sv[0]);    // make sure not to pass 
    return ( std::isdigit(ch) ? ch - '0' : 0 )  // negative values to isdigit()
        + digit_sum(sv.substr(1));
}

int main()
{
    char const *a{ "123a456" };
    std::cout << a << ": " << digit_sum(a) << '\n';  // 21

    char const *b{ "abc" };
    std::cout << b << ": " << digit_sum(b) << '\n';  // 0

    char const *c{ "0" };
    std::cout << c << ": " << digit_sum(c) << '\n';  // 0

    char const *d{ "" };
    std::cout << d << ": " << digit_sum(d) << '\n';  // 0
}

答案 1 :(得分:0)

这是更直接的C解决方案(无静态强制转换)。 它假定一种atoi行为,其中第一个非数字字符表示十进制字符串终止。

#include <stdio.h>
unsigned int sum(const char *s)
{
    if (s ==  NULL) return 0;
    if (s[0] ==  0) return 0;
    if (s[0] > '9') return 0;
    if (s[0] < '0') return 0;

    return (s[0]-'0')+sum(s+1);
}
int main(int argc, char **argv)
{
    char *x1 = "7934";
    char *x2 = "48d6";
    char *x3 = "appp";

    printf("%d\n",sum(x1));
    printf("%d\n",sum(x2));
    printf("%d\n",sum(x3));
}

答案 2 :(得分:0)

unsigned long long digit_sum(const std::string& s)
{
    if (s.empty())
        return 0;

    const char c = s.at(0);

    const int i = (c == '1' || c == '2' || c == '3' || c == '4' || c == '5'
                            || c == '6' || c == '7' || c == '8' || c == '9'
                  ) ? atoi(c) : 0;

    if (s.size() == 1)
        return i;
    else
        return i + digit_sum(s.substr(1));
}