Program liczb palindromowych w Java Używanie pętli while i for
Co to jest liczba palindromowa?
A Liczba palindromowa to liczba, która po odwróceniu pozostaje taka sama. Na przykład 131. Po odwróceniu cyfr liczba pozostaje ta sama. Liczba palindromowa ma symetrię odbicia na osi pionowej. Odnosi się do słowa, które ma tę samą pisownię, gdy jego litery są odwrócone.
Przykłady liczb palindromowych w Java
121, 393, 34043, 111, 555, 48084
Przykłady liczb palindromowych
LOL, MADAM
Algorytm liczb palindromowych
Poniżej znajduje się logika algorytmu liczb palindromowych Java:
- Pobierz numer wejściowy, który należy sprawdzić pod kątem bycia a Palindrom
- Skopiuj liczbę do zmiennej tymczasowej i odwróć ją.
- Porównaj liczbę odwróconą i oryginalną.
- Jeśli są takie same, liczba jest „liczbą palindromu”
- Inaczej liczba nie jest „liczbą palindromu”
Jak sprawdzić, czy liczba wejściowa jest palindromem, czy nie
Poniżej znajduje się program Palindromu w formacie Java w Pętla PODCZAS
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");
}
}
Dane wyjściowe kodu:
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
Program sprawdzający palindrom za pomocą pętli for
Poniżej znajduje Java program dla Palindromu przy użyciu pętli for
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");
}
}
Dane wyjściowe kodu:
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
