C++ - Decimal to binary converting

后端 未结 29 3647
一向
一向 2020-11-28 18:53

I wrote a \'simple\' (it took me 30 minutes) program that converts decimal number to binary. I am SURE that there\'s a lot simpler way so can you show me? Here\'s the code:<

29条回答
  •  时光说笑
    2020-11-28 19:34

    There is in fact a very simple way to do so. What we do is using a recursive function which is given the number (int) in the parameter. It is pretty easy to understand. You can add other conditions/variations too. Here is the code:

    int binary(int num)
    {
        int rem;
        if (num <= 1)
            {
                cout << num;
                return num;
            }
        rem = num % 2;
        binary(num / 2);
        cout << rem;
        return rem;
    }
    

提交回复
热议问题