C++ - Decimal to binary converting

后端 未结 29 3636
一向
一向 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:46

    Non recursive solution:

    #include 
    #include
    
    
    std::string toBinary(int n)
    {
        std::string r;
        while(n!=0) {r=(n%2==0 ?"0":"1")+r; n/=2;}
        return r;
    }
    int main()
    {
        std::string i= toBinary(10);
        std::cout<

    Recursive solution:

    #include 
    #include
    
    std::string r="";
    std::string toBinary(int n)
    {
        r=(n%2==0 ?"0":"1")+r;
        if (n / 2 != 0) {
            toBinary(n / 2);
        }
        return r;
    }
    int main()
    {
        std::string i=toBinary(10);
        std::cout<

提交回复
热议问题