2017-02-25 16 views
0

這不是「找到一個數字的迴文」!它有點扭曲:保持反轉號碼。並將其添加到原始編號。直到有一個迴文數字

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

回答

0

的問題是在你的PalinReverse方法。你while循環無限運行,因爲條件始終爲真。

更換

while (n>0)

while (n1>0)

您還應該學習如何調試程序。之後,你的生活將會輕鬆十倍。

+0

謝謝!它很尷尬,看看有多小的錯誤可以!還有一個你間接告訴我的錯誤!非常感謝你,是的,我應該學習:(必須停止懶惰 – user58736

+0

只是回覆,我會刪除這個帖子..現在不使用它! – user58736

+0

永遠不會刪除你的帖子,除非它有太多的否定票。沒有任何反對票,這意味着SD用戶對此感到滿意,如果您仍然刪除它,我將失去一些通過回答您的問題而獲得的代表點。 – VHS

相關問題