AcWing 445. 数字反转

问题描述:

给定一个整数,请将该数各个位上数字反转得到一个新数。

新数也应满足整数的常见形式,即除非给定的原数为零,否则反转后得到的新数的最高位数字不应为零。

输入格式:

输入共1行,1个整数N。

输出格式:

输出共1行,1个整数表示反转后的新数。

数据范围

∣ N ∣ ≤ 1 0 9 |N|≤10^9 N109

输入样例:

123

输出样例:

321

输入样例:

-380

输出样例:

-83

算法

(数学) O ( ) O() O();

思路:
巧用数学表达式res = res * 10 + n %10; 就是将最后一位取出,然后每次扩大10倍。此表达式也可以用于负数的情况。

时间复杂度分析

原题链接

C++代码:

#include <iostream>
#include <cmath>

using namespace std;

int n;

int main()
{
    cin >> n;
    
    int res = 0;
    
    while(n)
    {
        res = res * 10 + n % 10; 
        n /= 10;
    }
    
    cout << res << endl;
}

Java代码:

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String str = scanner.next().replaceAll("0+$", ""); //除去数字后面的0
        int n = Integer.parseInt(str);
        
        if (str.charAt(0) == '-') {
            System.out.print('-');
            for (int i = 1; i < str.length(); i++) {
                System.out.print(str.charAt(str.length() - i));
            }
        } else {
            for (int i = 1; i <= str.length(); i++) {
                System.out.print(str.charAt(str.length() - i));
            }
        }
    }
}

注:int 十进制:-2^31=-21 4748 3648 到 2^31-1=21 4748 3647。共10位,21亿。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值