替换数字中所有0为5的代码输出结果反转,求代码验证及修复方法
问题验证与解决方案
错误原因
- 顺序反转:你的代码通过
n % 10每次提取数字的最后一位,直接累加到sum中时是从右到左拼接数字,因此最终结果是倒序的。以输入1004为例,提取顺序为4、0、0、1,替换0为5后拼接得到4551,和预期的1554顺序相反。 - 原始值丢失:循环的终止条件是
n > 0,循环结束后n已经被除到0,因此输出的原始数字永远显示为0,无法正确展示输入值。
修复方案
方案1:纯数值运算实现(保留原有逻辑做调整)
在原有替换逻辑的基础上,再对替换后的倒序数字做一次反转,恢复正常顺序,同时提前保存原始输入值用于输出:
public class Replaceall0swith5 { public static void convertFive(int n) { // 提前保存原始输入值 int original = n; int digit, reversedSum = 0; // 第一轮:替换0为5,得到倒序的结果 while (n > 0) { digit = n % 10; if (digit == 0) { digit = 5; } reversedSum = reversedSum * 10 + digit; n = n / 10; } // 第二轮:反转回正常顺序 int result = 0; while (reversedSum > 0) { result = result * 10 + reversedSum % 10; reversedSum = reversedSum / 10; } System.out.print(original + " All 0's replaced with 5 " + result); } public static void main(String[] args) { Replaceall0swith5.convertFive(1004); } }
输入1004时输出为:1004 All 0's replaced with 5 1554,符合预期。
方案2:字符串替换实现(代码更简洁)
直接将数字转为字符串替换所有0字符为5,逻辑简单不易出错:
public class Replaceall0swith5 { public static void convertFive(int n) { String resultStr = String.valueOf(n).replace('0', '5'); int result = Integer.parseInt(resultStr); System.out.print(n + " All 0's replaced with 5 " + result); } public static void main(String[] args) { Replaceall0swith5.convertFive(1004); } }
内容的提问来源于stack exchange,提问作者Pankaj
相关产品推荐
相关产品推荐

