24h購物| | PChome| 登入
2012-12-24 17:11:44| 人氣860| 回應0 | 上一篇 | 下一篇

[UVA] 11403 - Binary Multiplication

推薦 0 收藏 0 轉貼0 訂閱站台

Problem: I

Binary Multiplication

           

 

All of us know simple multiplication rule.  Can we make a program to multiply two binary numbers? Well we can try.

 

 

Input specification:

Each case will define two binary strings (x & y). You can assume that length of each string will not exceed 30. The program will terminate with a 0 0.

 

Out put specification:

            Out put must be formatted like the following examples. You have to show the step by step procedure for the multiplication. Each result will be separated by an empty line.

 

Sample Input:

Output for Sample Input:

11 11

111 10

10 111

0 0

  11

  11

  --

  11

 11

----

1001

 

 111

  10

 ---

 000

111

----

1110

 

  10

 111

 ---

  10

 10

10

----

1110


這題完全不知道要搞什麼鬼,一堆錯誤題意。

#include <stdio.h>
#include <string.h>

int main() {
    char a[105], b[105];
    int first = 0;
    while(scanf("%s %s", a, b) == 2) {
        if(!strcmp("0", a) && !strcmp("0", b))
            break;
        int la = strlen(a), lb = strlen(b);
        int ans[105][105] = {};
        int i, j, ia, ja;
        for(i = lb-1, ia = 0; i >= 0; i--, ia++) {
            for(j = la-1, ja = 0; j >= 0; j--, ja++) {
                ans[ia][ia+ja] += (b[i]-'0')*(a[j]-'0');
                ans[lb][ia+ja] += ans[ia][ia+ja];
            }
            for(j = 0; j < 100; j++) {
                ans[i][j+1] += ans[i][j]/2;
                ans[i][j] %= 2;
            }
            for(j = 0; j < 100; j++) {
                ans[lb][j+1] += ans[lb][j]/2;
                ans[lb][j] %= 2;
            }
        }
        int mx = la > lb ? la : lb;
        int anslen;
        for(i = 99; i >= 0; i--)
            if(ans[lb][i])  break;
        if(i < 0)   i = 0;
        anslen = i+1;
        if(i+1 > mx)    mx = i+1;
        for(i = 0; i < mx-la; i++)
            putchar(' ');
        puts(a);
        for(i = 0; i < mx-lb; i++)
            putchar(' ');
        puts(b);
        int mx2 = la > lb ? la : lb;
        for(i = 0; i < mx-mx2; i++)
            putchar(' ');
        for(i = 0; i < mx2; i++)
            putchar('-');
        puts("");
        for(i = 0; i < lb; i++, puts("")) {
            for(j = 0; j < mx-i-la; j++)
                putchar(' ');
            for(j = i+la-1; j >= i; j--)
                putchar(ans[i][j]+'0');
        }
        for(i = 0; i < mx; i++)
            putchar('-');
        puts("");
        for(i = 0; i < mx-anslen; i++)
            putchar(' ');
        for(i = anslen-1; i >= 0; i--)
            putchar(ans[lb][i]+'0');
        puts("");
        puts("");
    }
    return 0;
}
/*
11 11
111 10
10 111
0 0
*/


台長: Morris
人氣(860) | 回應(0)| 推薦 (0)| 收藏 (0)| 轉寄
全站分類: 不分類 | 個人分類: UVA |
此分類下一篇:[UVA] 11804 - Argentina
此分類上一篇:[UVA][dp] 11032 - Function Overloading

是 (若未登入"個人新聞台帳號"則看不到回覆唷!)
* 請輸入識別碼:
請輸入圖片中算式的結果(可能為0) 
(有*為必填)
TOP
詳全文