筆試題——十進位制轉二進位制C/C++
阿新 • • 發佈:2018-12-28
原理:用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; }