码迷,mamicode.com
首页 > 其他好文 > 详细

Sicily 1381. a*b

时间:2014-10-16 14:06:42      阅读:135      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   color   io   os   for   sp   div   

Constraints

Time Limit: 1 secs, Memory Limit: 32 MB

Description

Give two positive integers a and b, please help us calculate a*b.

Input

The first line of the input is a positive integer T. T is the number of test cases followed.

Each test case contain two integer a,b (0<=a<=10^100, 0<=b<=10,000) given in one line.

Output

The output of each test case should consist of one line, contain the result of a*b.

Sample Input

1
2 7

Sample Output

14


没什么好说的,高精度乘法,字符串代替数字做乘法,将乘法转换为字符串加法。
举个栗子"1234" * "123" = "123400" +
"12340" + "12340" +
"1234" + "1234" + "1234"

#include <iostream>
#include <string>
using namespace std;

string add(string a, string b){
    if(b.length() > a.length()){
        string temp = a;
        a = b;
        b = temp;
    }
    a = "0" + a;
    int i, len = b.length();
    for(i = 0; i < a.length() - len; i++){
        b = "0" + b;
    }
    int in = 0, t;
    for(i = a.length() - 1; i >= 0; i--){
        t = in;
        in = (a[i] - 0 + b[i] - 0 + t)/10;
        a[i] = (a[i] - 0 + b[i] - 0 + t)%10 + 0;
    }
    if(a[0] == 0){
        a = a.substr(1, a.length()-1);
    }
    return a;
}

string multiply(string a, string b){
    string temp;
    if(b.length() > a.length()){
        temp = a;
        a = b;
        b = temp;
    }
    int i, j;
    string sum = "0";
    for(i = 0; i < b.length(); i++){
        temp = a;
        for(j = 0; j < b.length()-i-1; j++){
            temp = temp + "0";
        }
        for(j = 0; j < b[i]-0; j++){
            sum = add(sum, temp);
        }
    }
    return sum;
}


int main(){
    int t;
    cin >> t;
    while(t--){
        string a, b;
        cin >> a >> b;
        cout << multiply(a, b) << endl;
    }
    return 0;
}

 

Sicily 1381. a*b

标签:des   style   blog   color   io   os   for   sp   div   

原文地址:http://www.cnblogs.com/hunter-lee/p/4028330.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!