Zerojudge 基礎題庫a034 二進位制轉換
十進位轉二進位,現實生活中如何做到?
相信聰明的你,一定想到......
-------------------------------------------------------------------
假設題目是23:
先找二進位最大的位數
23 >= 1? Yes
23 >= 2? Yes
23 >= 4? Yes
23 >= 8? Yes
23 >= 16? Yes
23 >= 32? No
所以最大位數是第5位。
2^5 = 16,從十六開始減
23 >= 16? Yes -> 23-16=7,螢幕上 "1"
7 >= 8? No -> 螢幕上"10"
7 >= 4? Yes -> 7-4=3 ,螢幕上"101"
3 >= 2? Yes -> 3-2=1 ,螢幕上"1011"
1 >= 1? Yes -> 1-1=0 ,螢幕上"10111"
答案:10111
-------------------------------------------------------------------
看了這個例子,相信應該可以作答了。
加油!
當然這只是其中一種解法
還有很多解法等你去發掘!
當然:程式碼在此:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 | #include <iostream> #include <math.h> using namespace std; /* is (24 >= 1) yes is (24 >= 2) yes is (24 >= 4) yes is (24 >= 8) yes is (24 >= 16) yes is (24 >= 32) no is (24 >= 16) yes 24 - 16 = 8 "1" is (8 >= 8) yes "11" is (0 >= 4) no "110" is (0 >= 2) no "1100" is (0 >= 1) no "11000" */ int find_biggest(int question) { for (int i = 0; i <= i + 1; i++) { if (question >= pow(2,i)) { continue; } else { return pow(2,i)/2; } } } int cal_binary(int question) { /* is (24 >= 16) yes 24 - 16 = 8 "1" is (8 >= 8) yes "11" is (0 >= 4) no "110" is (0 >= 2) no "1100" is (0 >= 1) no "11000" */ int ans = question; int minius = find_biggest(question); while(minius != 1) { if (ans >= minius) { ans = ans - minius; minius = minius/2; cout << "1"; } else { minius = minius/2; cout << "0"; } } return ans; } int main() { int question; int ans; while(cin >> question) { ans = cal_binary(question); cout << ans << endl; } } |
留言
張貼留言