如何在递归函数中更改数字的数字?C++
How to change a number's digits in a recursive function? C++
我必须输入一个数字n
,a
数字和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。
要使事情变得更容易,您可以将数字转换为字符串(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();
}
相关文章:
- 比较并显示使用最小值(a,b)和最大值(a、b)升序排列的4个数字
- 为什么随机数生成器不在void函数中随机化数字,而在main函数中随机化
- 检查输入是否不是整数或数字
- 如何(从固定列表中)选择一个数字序列,该序列将与目标数字相加
- 如何用数字处理log(0)
- 最高有效数字侧的第N位
- 如何获取一个数字的前3位
- 查找最接近的大于当前数字的数字的索引
- 找到两对数字,使它们的乘积的绝对差最小化
- 我想做一个彼此不同但重复出现的数字
- 将数字转换为字母(例如:123 转换为一二三)
- C++如何计算用户输入的数字中的偶数位数
- 如何在C++中确定文本文件中的元素是字符还是数字
- 打印数字图案
- C++问题:用户认为数字1-100,程序提出问题不超过6次即可得到答案。无法正确
- 如何检查一个c++字符串中有多少相同的字符/数字
- 求出有多少个数字是完美平方,而sqrt()是L,R范围内的素数
- 将数字打印成文字
- 当使用比格式支持的精度更高的精度来显示数字时,会写出什么数据
- 在将数字随机生成为数组期间从内存输出随机数的数组