解题思路

  1. 这是一个整数反转问题,需要处理正负数的情况
  2. 解题步骤:
    • 保存原始数字的符号
    • 将数字转为正数处理
    • 通过取模和除法运算逐位提取数字并重新组合
    • 最后恢复符号

代码

#include <iostream>
using namespace std;

int main() {
    int num;
    cin >> num;
    
    // 处理符号
    bool isNegative = num < 0;
    if(isNegative) num = -num;
    
    // 反转数字
    int result = 0;
    while(num > 0) {
        result = result * 10 + num % 10;
        num /= 10;
    }
    
    // 恢复符号
    if(isNegative) result = -result;
    
    cout << result << endl;
    return 0;
}
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int num = sc.nextInt();
        
        // 处理符号
        boolean isNegative = num < 0;
        if(isNegative) num = -num;
        
        // 反转数字
        int result = 0;
        while(num > 0) {
            result = result * 10 + num % 10;
            num /= 10;
        }
        
        // 恢复符号
        if(isNegative) result = -result;
        
        System.out.println(result);
    }
}
def reverse_number(num):
    # 处理符号
    is_negative = num < 0
    if is_negative:
        num = -num
    
    # 转为字符串并反转
    result = int(str(num)[::-1])
    
    # 恢复符号
    return -result if is_negative else result

num = int(input())
print(reverse_number(num))

算法及复杂度

  • 算法:数学运算
  • 时间复杂度: - 为输入数字的大小,需要处理每一位数字
  • 空间复杂度: - 只需要常数额外空间