Does recursive function print in reverse?

荒凉一梦 提交于 2021-01-27 17:28:19

问题


#include <iostream>

using namespace std;
void convertToBinary(unsigned int n)
{
    if (n>0)
    {
        convertToBinary(n / 2);
        cout << n % 2;
    }
}
int main(){
    unsigned int n;
    cin >> n;
    convertToBinary(n);

}

Here is a function recursion that coverts from decimal to binary, for example If I give this function n equals to 10 the output is 1010, How come 1 is at the rightmost digit? It would be 0 since 10 % 2 = 0, then print 0 , so the expected output would be 101, since there's leading a 0.


回答1:


The data structure used by recursive calls is called as stack. Its working principle is last-in-first-out. So, not until your base condition i.e. (n > 0) is satisfied, convertToBinary re-cursively call before printing n%2 itself. When the base condition isn't fulfilled, convertToBinary commences to print binary values inversely because of stack structure.



来源:https://stackoverflow.com/questions/50083724/does-recursive-function-print-in-reverse

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!