【问题标题】:How to change a number's digits in a recursive function? C++如何在递归函数中更改数字的位数? C++
【发布时间】:2014-02-16 19:18:40
【问题描述】:

我必须输入一个数字n、一个a 数字和一个b 数字并输出数字n,其中所有a 数字都替换为b 数字。例如:

Input:
n = 1561525
a = 5
b = 9

Output:
n = 1961929

应该是递归的!我没有发布任何代码,因为我以非递归方式完成了它,但显然它甚至不接近我需要的。

感谢您的帮助!

【问题讨论】:

  • 至少可以指定编程语言
  • @u_mulder 哦..对不起...我刚刚做了。
  • 我不明白为什么它应该是递归的。在我看来,这不是一个特别适合递归的问题。
  • @SebastianNegraszus - 学校作业,这就是原因。

标签: c++ function recursion numbers digits


【解决方案1】:

检查一下,它可以工作,但可能是太多 C

int convert(int num, int a, int b)
{
    if( num )
    {
        int res = convert(num/10,a,b);
        int t = num%10;
        res *=10;
        t = t == a ? b:t;
        res = res + t;
        return res;
    }
    return 0;
}

将初始数字除以 10,直到什么都没有,然后将 a 替换为 b 再次构造它。

【讨论】:

  • 谢谢,它有效!不过有两个问题。首先,您能否详细说明一下 t = t == a ?乙:吨;行,因为我不太明白?其次,这看起来不像是返回自身的典型递归函数。它真的是一个吗?可以让它更像一个吗?
  • 1.这个表达式t==a ? b:t;叫做“三元if”如果你想使用它,谷歌它,或者用常规的if替换。 2.这是递归,这个函数调用它自己,只是在每次递归调用之后,应该对结果进行一些操作。
【解决方案2】:

为了方便起见,您可以将数字转换为字符串(C++ 中的char[])。然后,它是一个简单的迭代它并在每一步检查我们想要替换的数字是否在当前位置找到。对于一个可能的解决方案,这里有一个算法在 Python 中的实现——该语言的优点之一是它几乎可以像伪代码一样读取,并且移植到 C++ 应该相对简单:

def aux(n, a, b, i):
    if i == len(n):
        return ''
    elif n[i] == a:
        return b + aux(n, a, b, i+1)
    else:
        return n[i] + aux(n, a, b, i+1)

def change(n, a, b):
    return int(aux(str(n), str(a), str(b), 0))

它按预期工作:

change(1561525, 5, 9)
=> 1961929

【讨论】:

  • 非常感谢,但可以在单个函数中完成吗?只是我的作业是在某种软件上测试的,我不知道它有多严格。
  • @user3213110 我们需要额外的参数来使用递归进行循环。我认为使用辅助函数没有问题,只要主函数在预期输入、输出、名称和参数数量方面符合测试软件的要求
  • 我在将代码转换为 C++ 时遇到问题。我使用 char 在第一个函数中声明变量,但它一直告诉我我需要指针。即使我已经包含了<string> 库,lenstrlen 都不起作用……我迷路了。
  • @user3213110 专注于本质:aux 函数接收stringchar[],这取决于您,重要的是您需要通过索引访问每个元素,即您需要知道它的大小,并且在构建答案时,您需要一次连接一个字符。选择满足所有必需操作的数据表示,然后开始
【解决方案3】:

所以我能想到的最简单和最安全的方法是使用std::replace

int replace(int num, int d1, int d2) {
    string s = std::to_string(num);                     // convert to string
    std::replace( s.begin(), s.end(), d1+'0', d2+'0');  // call std::replace

    return atoi( s.c_str() );                           // return the int
}

现在,如果您真的必须使用递归(这里不需要),这里有一个可能的解决方案:

using std::string;

// recursive function, accepts a string, current index, c2 replaces c1
string replace_rec (string s, unsigned index, char c1, char c2) {

    // check if the it's still a valid index
    if (index < s.size()) {

        // if this is a char to be converted, do so
        if (s[index] == c1)
            s[index] = c2;

        // call itself but with an updated string and incremented index
        replace_rec(s, index+1, c1, c2);
    }

    // the last call will result in the string with all chars checked. return it
    return s;
}

// call this function with input, the num to be replaced and what with
int replace(int num, int d1, int d2) {

    string s = std::to_string(num);   // convert to string

    // convert the result back to int and return it.
    return atoi( replace_rec(s, 0, d1+'0', d2+'0').c_str() ); 
}

无论如何,您都可以像这样调用replace() 函数:

int main(){

    cout << replace (4578, 4, 9);   // output: 9578
    cin.get();
}

【讨论】:

    猜你喜欢
    • 2021-10-10
    • 1970-01-01
    • 2018-06-29
    • 2019-11-01
    • 2019-08-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-21
    • 2016-01-22
    相关资源
    最近更新 更多