【问题标题】:Keep Reversing the no. & adding it to the original no. until there is a Palindrome Number继续扭转号码。并将其添加到原始编号中。直到有一个回文数
【发布时间】:2017-07-16 13:45:59
【问题描述】:

这不是 “查找数字的回文”!比这有点扭曲:

第 1 步:反转原始数字的数字。

第 2 步:添加倒序号。

第 3 步:如果新数字是回文数,则打印输出。

限制是 15 步,如果它本身是回文,我们可以打印原始数字。我们必须在这个程序中使用函数调用。在这里,我使用了两个函数() - 首先是反转数字,其次是添加原始数字和反转的数字并检查总和是否是回文。

如果我能以任何方式改进这段长代码,请提出您的意见。

PS:Java 新手,尤其是函数调用!

谢谢!!这是代码,有点长!我很抱歉:(

import java.util.*;
public class PalindromicNumber
{
 public int PalinReverse(int n)
    {
     int n1=n;
     int x1=0, d1=0;
      while (n1>0)//just used to store the reverse of the original number
        {
          d1=n1%10;
          x1=(x1*10)+d1;
          n1=n1/10;
        }
    return x1;
     }

    public int PalinCheck (int n, int p)
      {
         int F=0;
         F=n+p; 
         int n1=F, x1=0, d1=0;

          while(n1>0)//checks if the sum of reversed no. and the original number is palindrome or not
           {
            d1=n1%10;
            x1=(x1*10)+d1;
            n1=n1/10;
           }
   if (x1==F)
       {
       System.out.println("The number"+ F +"is a Palindrome");
       return 1;
       }
   else 
       return F; //returns the sum if it is not a palindrome
    }

   public static void main (String args[])
     {
      Scanner sc=new Scanner(System.in);
      PalindromicNumber ob=new PalindromicNumber();

      System.out.println("Enter the original number");
      int n=sc.nextInt();

      int count=0;
      int n1=n, x1=0, d1=0;
        while(n1>0) //this checks if the original no. is a palindrome or not
           {
            d1=n1%10;
            x1=(x1*10)+d1;
            n1=n1/10;
           }

        if (x1==n)
        System.out.println("The original number="+n+"is a palindrome number");

        else

        for (count=0;count<15;count++)
           {
               int a=ob.PalinReverse(n);
               System.out.println("The reversed number is"+a);
               int b=ob.PalinCheck(n,a);
                if(b==1)
                {
                    System.out.println("The no. of steps it took was"count+1);
                    break;// the palindromic no. is now found out
                } 
                else 
                     n=b;//used to update the value of n
           }
    }
}

【问题讨论】:

    标签: java palindrome call-by-value


    【解决方案1】:

    问题出在您的PalinReverse 方法中。您的 while 循环无限运行,因为条件始终为真。

    替换

    while (n&gt;0)

    while (n1&gt;0)

    您还应该学习如何调试程序。在那之后,你的生活会轻松 10 倍。

    【讨论】:

    • 谢谢!看到小错误是多么令人尴尬!还有一个你间接告诉我的错误!非常感谢你,是的,我应该知道 :( 必须停止偷懒
    • 回复我就删了..现在不用了!
    • 永远不要删除你的帖子,除非它有太多的反对票。您的问题没有任何反对票,这意味着 SD 用户对此感到满意。如果您仍然删除它,我将失去一些通过回答您的问题获得的代表积分。
    • 哦,抱歉,我不知道...不过我只是编辑了一些小错误! :)
    猜你喜欢
    • 2020-12-31
    • 2015-04-07
    • 2022-01-21
    • 1970-01-01
    • 1970-01-01
    • 2021-10-21
    • 1970-01-01
    • 1970-01-01
    • 2015-02-24
    相关资源
    最近更新 更多