本文介绍了输入一个数字然后将其反转的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,所以我写了一个程序,要求用户输入一个数字,然后将其反转.我成功了,但是程序不会反转以 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.

这篇关于输入一个数字然后将其反转的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-17 15:46
查看更多