Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- int main(int argc, const char * argv[]) {
- int num;
- int idx = 0;
- int carries = 0;
- int bits[11]; // [0]:最右邊bit, [1]:右邊第二個bit, ...
- printf("Input a number -> ");
- scanf("%d", &num);
- int carry_stop = 0; // 0 means false
- do {
- int bit = num % 2; // 第一次是最右邊bit, 第二次是右邊第二個bit, ...
- if (!carry_stop) // 進位尚未停止的話,bit加1
- bit++;
- bits[idx++] = bit % 2; // 加1以後,記錄目前的第idx個bit (最右邊是第0個,右邊第二個是第1個,...)
- if (!carry_stop) {
- if (bit > 1) // 如果進位尚未停止的話,而且被加到2去的話
- carries++; // 進位數+1,之後繼續進位
- else
- carry_stop = 1; // 否則進位終止
- }
- num >>= 1; // num往右shift一個bit
- } while (num > 0);
- if (!carry_stop) // 別忘最後進位還沒停止的話,要在最左邊再生一個1出來
- bits[idx++] = 1;
- while (--idx >= 0) {
- printf("%d", bits[idx]);
- }
- printf(" %d", carries);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement