题解 | 反向输出一个四位数

反向输出一个四位数

https://www.nowcoder.com/practice/1f7c1d67446e4361bf4af67c08e0b8b0

import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        while (in.hasNextInt()) { // 注意 while 处理多个 case
            int a = in.nextInt();
            String strN =String.format("%04d",a);
            String result = new StringBuffer(strN).reverse().toString();

            System.out.print(result);

        }
    }
}

除了通过提取各个位数并重新组合的方式实现四位整数反向输出外,还可以使用 字符串操作字符串与数字转换 的方式来更简洁地完成这个任务。以下是几种不同的实现方式:

✅ 方法一:使用数学方法(如前所述)

这是最直观的方法,适用于对数值运算有要求的场景。

int n = 1230;

int thousandsDigit = (n / 1000) % 10; // 千位
int hundredsDigit = (n / 100) % 10;   // 百位
int tensDigit = (n / 10) % 10;       // 十位
int onesDigit = n % 10;              // 个位

int reversedNumber = onesDigit * 1000 + tensDigit * 100 + hundredsDigit * 10 + thousandsDigit;

System.out.printf("反向后的四位数为: %04d%n", reversedNumber);

✅ 方法二:使用字符串反转

将数字转换为字符串,然后使用字符串操作进行反转,最后格式化输出。

int n = 1230;
String strN = String.format("%04d", n); // 确保是四位数
String reversedStr = new StringBuilder(strN).reverse().toString();

System.out.println("反向后的四位数为: " + reversedStr);

特点:

  • 更加简洁。
  • 无需手动提取每一位。
  • 可读性强,适合处理固定长度数字。

✅ 方法三:使用字符数组

将数字转换为字符数组,再按逆序拼接成新字符串。

int n = 1230;
char[] digits = String.format("%04d", n).toCharArray();
char[] reversedDigits = new char[] {digits[3], digits[2], digits[1], digits[0]};
String reversedStr = new String(reversedDigits);

System.out.println("反向后的四位数为: " + reversedStr);

特点:

  • StringBuilder 更加底层可控。
  • 适用于需要逐字符处理的场景。

✅ 方法四:使用模除法+移位法(进阶版)

适用于嵌入式开发或对性能敏感的场景。

int n = 1230;

int digit1 = n % 10; n /= 10;
int digit2 = n % 10; n /= 10;
int digit3 = n % 10; n /= 10;
int digit4 = n % 10;

int reversed = digit1 * 1000 + digit2 * 100 + digit3 * 10 + digit4;

System.out.printf("反向后的四位数为: %04d%n", reversed);

特点:

  • 逻辑清晰,便于理解。
  • 避免了字符串操作,效率更高。

✅ 方法五:使用正则表达式(仅用于扩展思维)

虽然不推荐在简单任务中使用正则,但也可以作为一种思路拓展。

import java.util.regex.Matcher;
import java.util.regex.Pattern;

int n = 1230;
String strN = String.format("%04d", n);
Pattern pattern = Pattern.compile("(\\d)(\\d)(\\d)(\\d)");
Matcher matcher = pattern.matcher(strN);
if (matcher.matches()) {
    String reversed = matcher.group(4) + matcher.group(3) + matcher.group(2) + matcher.group(1);
    System.out.println("反向后的四位数为: " + reversed);
}

特点:

  • 过于复杂,不推荐用于本任务。
  • 适合用于解析复杂格式的数据时参考。

总结

数学模除法

✅ 是

中等

嵌入式、算法题

字符串反转

✅ 是

简单

快速开发、业务逻辑

字符数组

✅ 是

简单

需要字符级控制

正则表达式

✅ 是

复杂

数据格式解析

你可以根据实际需求选择合适的方法。对于日常开发来说,字符串反转是最简单、可读性最强的方式;而数学方法则更适合对性能要求较高的底层开发场景。

#牛客创作赏金赛##应届生,你找到工作了吗#
职保镖-扶你上马 文章被收录于专栏

知识分享,交天下朋友,扶你上马,送你一层,职业规划,面试指导、高薪谈判、背调辅助

全部评论

相关推荐

认真搞学习:这么良心的老板真少见
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务