输入一个数字然后将其反转

编程入门 行业动态 更新时间:2024-10-25 06:21:21
本文介绍了输入一个数字然后将其反转的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

好的,所以我写了一个程序,要求用户输入一个数字,然后将其反转.我成功了,但是程序不会反转以 0 结尾的数字.例如,如果我输入 1234,它将打印出 4321,但是如果我输入 1200,它将只输出 21.我尝试转换要成为输出的数字成字符串.请帮助我了解我在哪里做错了.请记住,我是这方面的初学者:).下面是我的代码.

Ok so I wrote a program which asks user to input a number and then reverse it. I was successful in it however the program does not reverses numbers that end with a 0. for example if i enter 1234 it will print out 4321 however if i input 1200 it will only output 21. I tried converting the number that is to become output into string. Please help me understand where I am doing it wrong. Just remember I am a beginner at this :). Below is my code.

import java.util.*; public class ReverseNumber { public static void main (String [] args) { Scanner n = new Scanner(System.in); int num; System.out.println("Please enter the number"); num = n.nextInt(); int temp = 0; int reverse = 0; String str = ""; System.out.println("The number before getting reversed " + num); while (num != 0) { temp = num % 10; reverse = reverse*10 + temp; num = num/10; str = Integer.toString(reverse); } //String str = Integer.toString(reverse); System.out.println("The reversed number is " + str); } }

推荐答案

您将反向数字存储为 int.1200 的相反数是 0021,但这只是 21 作为整数.您可以通过将每个数字单独转换为字符串来修复它.

You're storing your reversed number as an int. The reverse of 1200 is 0021, but that's just 21 as an int. You can fix it by converting each digit to a string separately.

更多推荐

输入一个数字然后将其反转

本文发布于:2023-11-16 06:26:40,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1601809.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:将其   数字

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!