首页 > 代码库 > Sicily 1381. a*b
Sicily 1381. a*b
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
12 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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。