题目
题目链接
解题思路
- 题目要求计算 \(rev(rev(x) + rev(y))\),其中 \(rev\) 操作是将数字翻转并去除前导零
- 需要实现以下步骤:
- 实现 \(rev\) 函数,完成数字翻转操作
- 计算 \(rev(x)\) 和 \(rev(y)\)
- 将两个翻转后的数字相加
- 对和进行再次翻转得到最终结果
- \(rev\) 函数实现要点:
- 通过取模运算获取每一位数字
- 通过乘10累加构建翻转后的数字
- 注意处理前导零的情况
代码
#include <iostream>
using namespace std;int rev(int x) {int result = 0;while (x > 0) {result = result * 10 + x % 10;x /= 10;}return result;
}int main() {int x, y;cin >> x >> y;int sum = rev(x) + rev(y);cout << rev(sum) << endl;return 0;
}
import java.util.Scanner;public class Main {public static int rev(int x) {int result = 0;while (x > 0) {result = result * 10 + x % 10;x /= 10;}return result;}public static void main(String[] args) {Scanner sc = new Scanner(System.in);int x = sc.nextInt();int y = sc.nextInt();int sum = rev(x) + rev(y);System.out.println(rev(sum));}
}
def rev(x):result = 0while x > 0:result = result * 10 + x % 10x //= 10return resultx, y = map(int, input().split())
sum = rev(x) + rev(y)
print(rev(sum))
算法及复杂度
- 算法:数学模拟
- 时间复杂度:\(\mathcal{O}(\log n)\),其中 \(n\) 是输入数字的最大值,主要来自数字翻转操作的位数遍历
- 空间复杂度:\(\mathcal{O}(1)\),只使用了常数额外空间