题解 | #数字翻转#
数字翻转
https://www.nowcoder.com/practice/bc62febdd1034a73a62224affe8bddf2
解题思路
- 题目要求计算
,其中
操作是将数字翻转并去除前导零
- 需要实现以下步骤:
- 实现
函数,完成数字翻转操作
- 计算
和
- 将两个翻转后的数字相加
- 对和进行再次翻转得到最终结果
- 实现
函数实现要点:
- 通过取模运算获取每一位数字
- 通过乘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 = 0
while x > 0:
result = result * 10 + x % 10
x //= 10
return result
x, y = map(int, input().split())
sum = rev(x) + rev(y)
print(rev(sum))
算法及复杂度
- 算法:数学模拟
- 时间复杂度:
,其中
是输入数字的最大值,主要来自数字翻转操作的位数遍历
- 空间复杂度:
,只使用了常数额外空间