笔试题——十进制转二进制C/C++

原理:用2辗转相处待转换的十进制的整数部分,直至结果为1.将余数和最后的1从下向上写出来就是结果。


#include <stdio.h>

int convert(int n)
{
    if(n == 1)              
    {
        printf("%d ",n);
        return 0;
    }
        printf("%d ",n%2)
    else if(n == 0)
        return 0;
    else
    {
        convert(n/2);
        printf("%d ",n%2);
    }
}

int main(int argc, char **argv)
{
    int n,i;
    scanf("%d",&n);

    convert(n);
    /*
    for(i = 0;i < strlen(a);i++)
    {
        printf()
    }
    */
    return 0;
}

#include <iostream>
#include <vector>
#include <stack>

using namespace std;

void fconvert(long n,vector<long> &bit)
{
    stack<long> tempstack;
    long temp = n;
    while(temp != 1)
    {
        long temp1 = temp % 2;
        tempstack.push(temp1);
        temp = temp/2;
    }
    tempstack.push(1);
    while(tempstack.empty() == false)
    {
        long n = tempstack.top();
        bit.push_back(n);
        tempstack.pop();
    }
        
}

int main(int argc, char **argv)
{
    vector<long> bit;
    fconvert(11,bit);
    vector<long>::iterator it = bit.begin();
    while(it != bit.end())
    {
        cout << *it;
        it++;
    }
    cout << endl;
    return 0;
}

 

    原文作者:进制转换
    原文地址: https://blog.csdn.net/Zhanganliu/article/details/82597420
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞