做作业的时候,邻座的小盆友问你:“五乘以七等于多少?”你应该不失礼貌地围笑着告诉他:“五十三。”本题就要求你,对任何一对给定的正整数,倒着输出它们的乘积。
输入格式:
输入在第一行给出两个不超过 1000 的正整数 A 和 B,其间以空格分隔。
输出格式:
在一行中倒着输出 A 和 B 的乘积。
输入样例:
5 7
输出样例:
53
思路一:由于数字很小,直接处理。
#include <cstdio>
int main() {
int a, b;
scanf("%d %d", &a, &b);
int c = a * b, ans = 0;
while (c) {
int temp = c % 10;
ans = temp + ans * 10;
c /= 10;
}
printf("%d", ans);
return 0;
}
思路二:把结果数字转换为字符串,再逆序输出。这个方法一开始用的比较麻烦,后面参考了柳神的代码,学会了to_string函数和reverse函数。
#include <cstdio>
#include <string>
#include <algorithm>
using namespace std;
int main() {
int a, b;
scanf("%d %d", &a, &b);
string s = to_string(a * b);//to_string将数字常量转换为字符串
reverse(s.begin(), s.end());//将元素逆序
printf("%d", stoi(s));//stoi函数将数字字符串转换成int输出
return 0;
}
参考链接:link