C++ - Decimal to binary converting

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

    using bitmask and bitwise and .

    string int2bin(int n){
        string x;
        for(int i=0;i<32;i++){
            if(n&1) {x+='1';}
            else {x+='0';}
            n>>=1;
        }
        reverse(x.begin(),x.end());
        return x;
    }
    

提交回复
热议问题