C++ - Decimal to binary converting

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

    // function to convert decimal to binary
    void decToBinary(int n)
    {
        // array to store binary number
        int binaryNum[1000];
    
        // counter for binary array
        int i = 0;
        while (n > 0) {
    
            // storing remainder in binary array
            binaryNum[i] = n % 2;
            n = n / 2;
            i++;
        }
    
        // printing binary array in reverse order
        for (int j = i - 1; j >= 0; j--)
            cout << binaryNum[j];
    }
    

    refer :- https://www.geeksforgeeks.org/program-decimal-binary-conversion/

    or using function :-

    #include
    using namespace std;
    
    int main()
    {
    
        int n;cin>>n;
        cout<(n).to_string()<

    or using left shift

    #include
    using namespace std;
    int main()
    {
        // here n is the number of bit representation we want 
        int n;cin>>n;
    
        // num is a number whose binary representation we want
        int num;
        cin>>num;
    
        for(int i=n-1;i>=0;i--)
        {
            if( num & ( 1 << i ) ) cout<<1;
            else cout<<0;
        }
    
    
    }
    

提交回复
热议问题