Palindroomi numbriprogramm sisse Java Kasutades while & for Loop
Mis on palindroomi number?
A Palindroomi number on arv, mis ümberpööramisel jääb samaks. Näiteks 131. Kui selle numbrid on ümber pööratud, jääb see samaks. Palindroomi numbril on vertikaalteljel peegeldussümmeetria. See viitab sõnale, millel on sama kirjapilt, kui selle tähed on vastupidised.
Palindroomi numbri näited Java
121, 393, 34043, 111, 555, 48084
Näited palindroomi numbrist
LOL, MADAM
Palindroomi numbri algoritm
Allpool on palindroomi numbrite algoritmi loogika Java:
- Hankige sisendnumber, mida tuleb kontrollida, kas see on a Palindroomid
- Kopeerige number ajutiseks muutujaks ja pöörake see tagasi.
- Võrrelge ümberpööratud ja algset numbrit.
- Kui need on samad, on number "palindroom number"
- Muu number ei ole "palindroom number"
Kuidas kontrollida, kas sisendnumber on palindroom või mitte
Allpool on Palindroomi programm Java koos WHILE Loop
package com.guru99; public class PalindromeNum { public static void main(String[] args) { int lastDigit,sum=0,a; int inputNumber=171; //It is the number to be checked for palindrome a=inputNumber; // Code to reverse a number while(a>0) { System.out.println("Input Number "+a); lastDigit=a%10; //getting remainder System.out.println("Last Digit "+lastDigit); System.out.println("Digit "+lastDigit+ " was added to sum "+(sum*10)); sum=(sum*10)+lastDigit; a=a/10; } // if given number equal to sum than number is palindrome otherwise not palindrome if(sum==inputNumber) System.out.println("Number is palindrome "); else System.out.println("Number is not palindrome"); } }
Koodi väljund:
Input Number 171 Last Digit 1 Digit 1 was added to sum 0 Input Number 17 Last Digit 7 Digit 7 was added to sum 10 Input Number 1 Last Digit 1 Digit 1 was added to sum 170 Number is palindrome
Programm palindroomi kontrollimiseks, kasutades tsüklit
Allpool on Java programm Palindroomi jaoks, kasutades tsüklit
package com.guru99; public class PalindromeNum { public static void main(String[] args) { int lastDigit,sum=0,a; int inputNumber=185; //It is the number to be checked for palindrome a=inputNumber; // Code to reverse a number for( ;a != 0; a /= 10 ) { System.out.println("Input Number "+a); lastDigit=a%10; //getting remainder System.out.println("Last Digit "+lastDigit); System.out.println("Digit "+lastDigit+ " was added to sum "+(sum*10)); sum=(sum*10)+lastDigit; a=a/10; } // if given number equal to sum than number is palindrome otherwise not palindrome if(sum==inputNumber) System.out.println("Number is palindrome "); else System.out.println("Number is not palindrome"); } }
Koodi väljund:
Input Number 185 Last Digit 5 Digit 5 was added to sum 0 Input Number 1 Last Digit 1 Digit 1 was added to sum 50 Number is not palindrome