关键字:两个数的每一位相乘求和,获得一个数的每一位
题目描述
写个算法,对2个小于1000000000的输入,求结果。 特殊乘法举例:123 * 45 = 1*4 +1*5 +2*4 +2*5 +3*4+3*5
输入描述:
两个小于1000000000的数
输出描述:
输入可能有多组数据,对于每一组数据,输出Input中的两个数按照题目要求的方法进行运算后得到的结果。
示例1
输入
123 45
输出
54
代码:
【数位拆解法:】
#include <iostream>
#include <fstream>
#include <cmath>
using namespace std;
int cal(int *x1, int x){
int idx = 0;
while(x > 0){
x1[idx++] = x % 10;
x /= 10;
}
return idx;
}
int main(){
// freopen("a.txt", "r", stdin);
double a, b;
int a1[11], b1[11];
int k1, k2, ans;
while(cin >> a >> b){
ans = 0;
k1 = cal(a1, a);
k2 = cal(b1, b);
for(int i = 0; i < k1; ++i){
for(int j = 0; j < k2; ++j){
ans += a1[i] * b1[j];
}
}
cout << ans << endl;
}
return 0;
}
直接用字符串:
大神的代码….orz…
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main(){
// freopen("a.txt", "r", stdin);
string s1, s2;
while(cin >> s1 >> s2){
int ans = 0;
int len1 = s1.length();
int len2 = s2.length();
for(int i = 0; i < len1; ++i){
for(int j = 0; j < len2; ++j){
ans += (s1[i] - '0') * (s2[j] - '0');
}
} cout << ans << endl;
}
return 0;
}