嗨,大家好我最近学习了递归,我尝试了很多返回类型,似乎我在过去的一两天里一直在努力解决这个问题.可悲的是,我没有运气.
这个想法是:
码:
string convert(int value, int b){
stringstream s;
//Once the value is 0 or 1 it returns the whole result
if(value ==0 || value ==1)
return s.str();
else
{
//I store the remainder results in the stringstream and call the function again
s<<convert(value/b,b)<<value%b;
}
}
Run Code Online (Sandbox Code Playgroud)
在处理递归时,一个关键的a-ha时刻是,用户调用的函数几乎从来没有意义递归.使用递归通常意味着使用递归辅助函数.
/* this is the helper function */
void convert(stringstream& s, int value, int b)
{
if (value == 0) return;
convert(s, value / b, b); /* recursive call */
s << (char)('0' + value % b);
}
/* this is the function the user calls */
string convert(int value, int b)
{
stringstream s;
convert(s, value / b, b); /* calls helper, not itself */
s << (char)('0' + value % b);
return s.str();
}
Run Code Online (Sandbox Code Playgroud)
现在,切入点处理一些特殊情况:
"0"而不是空字符串.stringstream.stringstream缓冲区.这些是您不希望递归函数执行的步骤.在每次递归调用时复制字符串或字符串流是非常浪费的.
此外,字符串流在这里并不真正有用,因为没有真正的格式化输出发生.所以我会这样做:
void convert(string& s, int value, int b)
{
if (value == 0) return;
convert(s, value / b, b); /* recursive call */
s.append('0' + value % b);
}
/* this is the function the user calls */
string convert(int value, int b)
{
string s;
convert(s, value / b, b); /* calls helper, not itself */
s.append('0' + value % b);
return s;
}
Run Code Online (Sandbox Code Playgroud)