0

「数の回文を求める」ではありません!それよりも少しねじれています。

ステップ 1: 元の数字の桁を逆にします。

ステップ 2: 逆数を追加します。

ステップ 3: 新しい数が回文数の場合、出力を印刷します。

制限は 15 ステップです。それ自体が回文である場合、元の数を印刷できます。このプログラムでは関数呼び出しを使用する必要があります。ここでは、2 つの functions() を使用しました。FIRST を使用して数値を逆にし、SECOND を使用して元の数値と反転した数値を加算し、合計が回文であるかどうかを確認します。

この長いコードを何らかの方法で改善できるかどうか、ご意見をお聞かせください。

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
           }
    }
}
4

1 に答える 1