如何在递归函数中更改数字的数字?C++

How to change a number's digits in a recursive function? C++

本文关键字:数字 C++ 递归函数      更新时间:2023-10-16

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

Input:
n = 1561525
a = 5
b = 9
Output:
n = 1961929

应该是递归的!我没有以非恢复方式发布任何代码,但显然它甚至还不接近我的需求。

感谢您的帮助!

检查一下,它有效,但也许是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的初始数字,直到没有剩下的数字,然后再次构造它用b。

替换为a

要使事情变得更容易,您可以将数字转换为字符串(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

,我能想到的最简单,最安全的方法是使用 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();
}