Related
public class Car {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
System.out.println(n+"!="+factorial(n));
}
public static int factorial(int num) {
return (num == 0) ? 1 : num * factorial (num - 1);
}
}
how make this code to text in console 3! = 1*2*3 = 6?
Don't use recursion for this. Besides, it isn't really efficient or necessary.
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int fact = 1;
String s = n + "! = 1";
for (int i = 2; i <= n; i++) {
fact *= i;
s += "*" + i;
}
s += " = ";
System.out.println(s + fact);
There can be many ways to do it e.g. you can build the required string or print the trail while calculating the factorial. In the following example, I have done the former.
As an aside, you should check the input whether it is a positive integer.
import java.util.Scanner;
public class Car {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter a positive integer: ");
int n = in.nextInt();
if (n >= 0) {
StringBuilder strFact = new StringBuilder();
int fact = factorial(n, strFact);
if (strFact.length() > 0) {
// Delete the last '*'
strFact.deleteCharAt(strFact.length() - 1);
System.out.println(n + "!= " + strFact + " = " + fact);
} else {
System.out.println(n + "!= " + fact);
}
} else {
System.out.println("This is an invalid input.");
}
}
public static int factorial(int num, StringBuilder strFact) {
int fact;
if (num == 0) {
fact = 1;
} else {
fact = num * factorial(num - 1, strFact);
strFact.append(num + "*");
}
return fact;
}
}
A sample run:
Enter an integer: 3
3!= 1*2*3 = 6
This is the program that checks if the input integer is binary or not, now I need to create a loop that will prompt the user to renter integers until binary number is entered.
import java.util.Scanner;
public class BinaryNumbers {
public static void main(String[] args) {
int value, userValue;
int binaryDigit = 0, notBinaryDigit = 0;
Scanner scan = new Scanner(System.in);
System.out.println("Please enter positive integers: ");
userValue = scan.nextInt();
value = userValue;
while (userValue > 0) {
if ((userValue % 10 == 0) || (userValue % 10 == 1)) {
binaryDigit++;
} else {
notBinaryDigit++;
}
userValue = userValue / 10;
}
if (notBinaryDigit == 0) {
System.out.println(value + " is a Binary Number.");
} else {
System.out.println(value + " is not a Binary Number.");
}
}
}
Why not using Regular Expressions?
All those checking on user inputs by assuming them as numbers (by calling Scanner#nextInt or Scanner#nextFloat or ...) are very breakable. How can be so sure user won't enter anything wrong?
It's better to hold the user input in a String variable and check it against being binary integer (which has to be 32 bit at most as defined in many languages such as java) using Regex is more safe:
import java.util.Scanner;
public class CheckBinaryInteger {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
boolean isValid = false;
String userInput = "";
do {
System.out.print("Please Enter a binary integer: ");
userInput = sc.next();
isValid = userInput != null && !userInput.trim().isEmpty()
&& userInput.matches("[01]{1,32}");//assume every digit as one bit
if(!isValid)
System.out.println("invalid binary integer entered! ");
}while(!isValid);
System.out.println("Valid input: "+userInput);
}
}
Hope this helps.
import java.util.Scanner;
public class BinaryNumbers {
public static void main(String[] args) {
int value, userValue;
Scanner scan = new Scanner(System.in);
while(true){
int binaryDigit = 0, notBinaryDigit = 0;
System.out.println("Please enter positive integers: ");
userValue = scan.nextInt();
value = userValue;
while (userValue > 0) {
if ((userValue % 10 == 0) || (userValue % 10 == 1)) {
binaryDigit++;
} else {
notBinaryDigit++;
}
userValue = userValue / 10;
}
if (notBinaryDigit == 0) {
System.out.println(value + " is a Binary Number.");
return; //does the trick ;)
} else {
System.out.println(value + " is not a Binary Number.");
}
}
}
}
A simple return can end the program then and there :)
import java.util.Scanner;
class calculatePremium
{
public static void main(String[] args) {
int value, userValue;
int binaryDigit = 0, notBinaryDigit = 0;
Scanner scan = new Scanner(System.in);
while(true) /*use a while loop to iterate till you get the binary number*/
{
binaryDigit = 0; notBinaryDigit = 0;
System.out.println("Please enter positive integers: ");
userValue = scan.nextInt();
value = userValue;
while (userValue > 0) {
if ((userValue % 10 == 0) || (userValue % 10 == 1)) {
binaryDigit++;
} else {
notBinaryDigit++;
}
userValue = userValue / 10;
}
if (notBinaryDigit == 0) {
System.out.println(value + " is a Binary Number.");
break; /* breaks out of loop when gets the correct input */
} else {
System.out.println(value + " is not a Binary Number.\n");
}
}
}
}
You just need to use a loop till you get a binary number.
Hope it helps.
import java.util.Scanner;
public class BinaryNumbers {
public static void main(String[] args) {
int value, userValue;
int binaryDigit = 0, notBinaryDigit = 0;
Scanner scan = new Scanner(System.in);
while(true)
{
System.out.println("Please enter positive integers: ");
userValue = scan.nextInt();
value = userValue;
while (userValue > 0)
{
if ((userValue % 10 == 0) || (userValue % 10 == 1))
binaryDigit++;
else
notBinaryDigit++;
userValue = userValue / 10;
}
if (notBinaryDigit == 0)
{
System.out.println(value + " is a Binary Number.");
break;
}
else
System.out.println(value + " is not a Binary Number.");
}
}
}
Though the problem seemed simple, here it is :-
A Kaprekar number is a positive whole number n with d digits, such that when we split its square into two pieces - a right hand piece r with d digits and a left hand piece l that contains the remaining d or d−1 digits, the sum of the pieces is equal to the original number (i.e. l + r = n).
The Task
You are given the two positive integers p and q, where p is lower than q. Write a program to determine how many Kaprekar numbers are there in the range between p and q (both inclusive) and display them all.
Input Format
There will be two lines of input: p, lowest value q, highest value
Constraints:
0<p<q<100000
Output Format
Output each Kaprekar number in the given range, space-separated on a single line. If no Kaprekar numbers exist in the given range, print INVALID RANGE.
I could not clear the test cases in the range
22223
99999
In the above range the follwoing numbers should have been generated :-
77778 82656 95121 99999
Here is my code :-
import java.io.*;
import java.util.*;
public class Solution {
public static void main(String[] args) {
/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
Scanner scan = new Scanner(System.in);
int p = scan.nextInt();
int q = scan.nextInt();
boolean exist = false;
if(q <= p){
System.out.println("INVALID RANGE");
}
int m = 0,n = 0;
long sqr = 0;
String numb = "";
String[] digits = new String[2];
for(int i = p; i <= q; i++){
if(i == 1)System.out.print(1 + " ");
else{
sqr = i*i;
numb = String.valueOf(sqr);// Changing it into a string.
if(numb.length() % 2 == 0){
digits[0] = numb.substring(0, numb.length()/2);//Splitting it into two parts
digits[1] = numb.substring(numb.length()/2);
}else{
digits[0] = numb.substring(0, (numb.length() - 1)/2);
digits[1] = numb.substring((numb.length() -1)/2);
}
if(digits[0] == "" )
m = 0;
if(digits[1] == "")
n = 0;
if(!digits[1].equals("") && !digits[0].equals("")){
m = Integer.parseInt(digits[0]);
n = Integer.parseInt(digits[1]);
}
if(i == (m + n) ){ //Testing for equality
System.out.print(i + " ");
exist = true;
}
}
}
if(exist == false){// If exist is never modified print Invalid Range.
System.out.println("INVALID RANGE");
}
}
}
import java.util.*;
public class Kaprekar
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter a number");
int num=sc.nextInt();
int sq=num*num; String sq1=Integer.toString(sq);
int mid=(Integer.toString(sq).length())/2;
int rem=sq%((int)Math.pow(10,sq1.length()-mid));
int quo=sq/((int)Math.pow(10,sq1.length()-mid));
int sum=rem+quo;
if(sum==num)
{System.out.println("Kaprekar");}else{System.out.println("Not Kaprecar");}
}
}
Changing the type of Loop index i from int to long fixed the problem.
The square computation of i*i was overflowing the upper limit of int so by changing it to long we were able to get the required computation done.
Thanks to Rup for pointing this out.
The code which cleared all the test cases is here :-
import java.io.*;
import java.util.*;
public class Solution {
public static void main(String[] args) {
/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
Scanner scan = new Scanner(System.in);
int p = scan.nextInt();
int q = scan.nextInt();
boolean exist = false;
if(q <= p){
System.out.println("INVALID RANGE");
return;
}
int m = 0,n = 0;
long sqr = 0;
String numb = "";
String[] digits = new String[2];
for(long i = p; i <= q; i++){
if(i == 1)System.out.print(1 + " ");
else{
sqr = i*i;
numb = String.valueOf(sqr);
if(numb.length() % 2 == 0){
digits[0] = numb.substring(0, numb.length()/2);
digits[1] = numb.substring(numb.length()/2);
}else{
digits[0] = numb.substring(0, (numb.length() - 1)/2);
digits[1] = numb.substring((numb.length() -1)/2);
}
if(digits[0] == "" )
m = 0;
if(digits[1] == "")
n = 0;
if(!digits[1].equals("") && !digits[0].equals("")){
m = Integer.parseInt(digits[0]);
n = Integer.parseInt(digits[1]);
}
if(i == (m + n) ){
System.out.print(i + " ");
exist = true;
}
}
}
if(exist == false){
System.out.println("INVALID RANGE");
}
}
}
import java.io.*;
import java.math.*;
import java.util.*;
class Kaprekar {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int p = scanner.nextInt();
int q = scanner.nextInt();
long i,n,s,a,c,k,d,e=0;
for(i=p;i<=q;i++)
{
k=i;d=0;
while(k!=0)
{
d++;
k=k/10;
}
c=0;s=0;n=i*i;
while(n!=0)
{
a=n%10;
n=n/10;
s=s+ (int)Math.pow(10,c)*a;
c++;
if(n+s==i&&(c==d||c==d-1)&&s!=0)
{
System.out.print(i+" ");
e++; break;
}
}
}
if(e==0)
{
System.out.println("INVALID RANGE");
}
scanner.close();
}
}
this is my program:
public class ArmstrongNumber {
public static void main(String args[]) {
int n = 0, temp = 0, r = 0, s = 0;
Scanner in = new Scanner(System.in);
System.out.println("Enter a number ");
if (in.hasNextInt()) {
n = in.nextInt(); // if there is another number
} else {
n = 0;
}
temp = n;
while (n != 0) {
r = n % 10;
s = s + (r * r * r);
n = n / 10;
}
if (temp == s) {
System.out.println(n + " is an Armstrong Number");
} else {
System.out.println(n + " is not an Armstrong Number");
}
}
}
output:
Exception in thread "main" java.lang.NoClassDefFoundError
I tried it using DataInputStream but still getting same error.
// To check the given no is Armstrong number (Java Code)
class CheckArmStrong{
public static void main(String str[]){
int n=153,a, b=0, c=n;
while(n>0){
a=n%10; n=n/10; b=b+(a*a*a);
System.out.println(a+" "+n+" "+b); // to see the logic
}
if(c==b) System.out.println("Armstrong number");
else System.out.println(" Not Armstrong number");
}
}
Find any digit is Armstrong number or not using loop
for(int arm_num = 0 ; arm_num < 100000 ; arm_num++)
{
String[] data = String.valueOf(arm_num).split("(?<=.)");
int lngth = String.valueOf(arm_num).length();
int arm_t_num = 0;
int ary[] = new int[lngth];
for(int i = 0 ; i < lngth ; i++)
{
ary[i] = Integer.parseInt(data[i]);
for(int x = 0 ; x < lngth-1 ; x++)
{
ary[i] = ary[i] * Integer.parseInt(data[i]);
}
arm_t_num+=ary[i];
}
if(arm_num == arm_t_num)
{
System.out.println("Number is ArmStrong : "+arm_num);
}
}
you need to set CLASS_PATH variable and point it to where ever your class file is
then this should work
I have tried it locally, refer my answer to check how to set class path and how to compile and run java code using command prompt
//This is my program to check whether the number is armstrong or not!!
package myprogram2;
public class Myprogram2 {
public static void main(String[] args)
{
String No="407";
int length_no=No.length();
char[] S=new char[length_no];
int[] b = new int[length_no];
int arm=0;
for(int i=0;i<length_no;i++)
{
S[i]=No.charAt(i);
b[i]=Character.getNumericValue(S[i]);
//System.out.print(b[i]);
arm=arm + (b[i]*b[i]*b[i]);
System.out.println(arm);
}
//System.out.println(" is the number \n now Checking for its Armstrong condition");
int orgno = Integer.parseInt(No);
if (orgno==arm)
System.out.println("YESm its an armstrong");
else
System.out.println("\n<<Not an armstrong>>");
//System.out.println(length_no);
System.out.println("Original number is "+orgno);
System.out.println("Sum of cubes "+arm);
}
}
There are a couple of nice String-based solutions and numeric solutions with single-letter variable names.
Consider this to make sense of how it works numerically, which includes a couple of interesting numeric tricks:
import java.io.*;
public class Armstrong
{
public static void main(String args[]) throws IOException
{
InputStreamReader read = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(read);
int modifiedNumber, originalNumber, modifiedNumberWithUnitsDigitZero,
unitsDigit, runningSum;
System.out.println("Enter your number:");
modifiedNumber = Integer.parseInt(in.readLine());
runningSum = 0;
originalNumber = modifiedNumber;
while(modifiedNumber > 0)
{
modifiedNumberWithUnitsDigitZero = modifiedNumber / 10 * 10;
unitsDigit = modifiedNumber - modifiedNumberWithUnitsDigitZero;
runningSum += unitsDigit * unitsDigit * unitsDigit;
modifiedNumber = modifiedNumber / 10;
}
System.out.println("The number " + originalNumber
+ (originalNumber == runningSum ? " IS" : " is NOT")
+ " an Armstrong number because sum of cubes of digits is " + runningSum);
}
}
import java.util.Scanner;
public class Amst {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
System.out.println("Enter The No. To Find ArmStrong Check");
int i = sc.nextInt();
int sum = 0;
for(int j = i; j>0 ; j = j/10){
sum = sum + ((j%10)*(j%10)*(j%10));
}
if(sum == i)
System.out.println("Armstrong");
else
System.out.println("Not Armstrong");
}
}
For 'N' digit amstrong number
package jjtest;
public class Amstrong {
public static void main(String[] args) {
// TODO Auto-generated method stub
int num=54748;
int c=0;
int temp=num;
int b=1;
int length = (int)(Math.log10(num)+1);
while(num>0){
int r = num%10;
num=num/10;
int a =1;
for(int i=1;i<=length;++i){
b=b*r;
}
c = c + b;
b=1;
}
System.out.println(c);
if(c==temp){
System.out.println("its an amstrong number");
}else{
System.out.println("its not an amstrong number");
}
}
}
This is the simple logic for Armstrong number program :
for (int i = number; i > 0; i = i / 10)
{
remainder = i % 10;
sum = sum + remainder * remainder * remainder;
}
if(sum == number)
{
System.out.println("\n" + number + " is an Armstrong Number\n");
}
Reference :
http://topjavatutorial.com/java/java-programs/java-program-to-check-if-a-number-is-armstrong-number/
import java.util.Scanner;
/* a number is armstrong if the sum of cubes if individual digits of
a number is equal to the number itself.for example, 371 is
an armstrong number. 3^3+7^3+1^3=371.
some others are 153,370,407 etc.*/
public class ArmstrongNumber {
public static void main(String args[]) {
int input, store, output=0, modolus;
Scanner in = new Scanner(System.in);
System.out.println("Please enter a number for ckecking.");
input = in.nextInt();
store = input;
while(input != 0) {
modolus = input % 10;
output = output + (modolus * modolus * modolus);
input = input / 10;
}
System.out.println(output);
if(store == output) {
System.out.println("This is an armstrong number.");
} else {
System.out.println("This is not an armstrong number.");
}
in.close();
}
}
import java.util.*;
public class ArmstrongNumber
{
public static void main( String[] args )
{
int n = 0, temp = 0, r = 0, s = 0;
Scanner in = new Scanner(System.in);
System.out.println("Enter a number ");
if (in.hasNextInt()) {
n = in.nextInt(); // if there is another number
} else {
n = 0;
}
temp = n;
while (n != 0) {
r = n % 10;
s = s + (r * r * r);
n = n / 10;
}
if (temp == s) {
System.out.println(temp + " is an Armstrong Number");
} else {
System.out.println(temp + " is not an Armstrong Number");
}
}
}
You missed to import java.util package
Change n to temp in S.O.P
import java.util.Scanner;
public class AmstrongNumber {
public static void main(String[] args) {
System.out.println("Enter the number");
Scanner scan=new Scanner(System.in);
int x=scan.nextInt();
int temp2=0;
String s1 = Integer.toString(x);
int[] a = new int[s1.length()];
int[] a1 = new int[s1.length()];
for (int i = 0; i < s1.length(); i++){
a[i] = s1.charAt(i)- '0';
int temp1=a[i];
a1[i]=temp1*temp1*temp1;
}
for (int i = 0; i < s1.length(); i++){
temp2=temp2+a1[i];
if(i==s1.length()-1){
if(x==temp2){
System.out.println("Amstrong num");
}else{
System.out.println("Not !");
}
}
}
}
}
private static boolean isArmstrong(int num) {
int totalSum = 0;
int copyNum = num;
while (num != 0) {
int reminder = num % 10;
int cubeOfReminder = reminder * reminder * reminder;
totalSum = totalSum + cubeOfReminder;
num = num / 10;
}
if (copyNum == totalSum)
return true;
return false;
}
public class Testamstrong
{
public static void main(String...strings) {
int num = 153,temp;
temp = num;
if(temp == amstrongNumber(num)) {
System.out.println("Number is amstrong number...");
}
else {
System.out.println("Number is not amstrong number...");
}
}
public static int amstrongNumber(int num) {
int count=0,sum=0;
count = String.valueOf(num).length();
char[] ch = String.valueOf(num).toCharArray();
for(char ch1:ch) {
int num1 = Character.getNumericValue(ch1);
sum += Math.pow(num1, count);
}
return sum;
}
}
Find Armstrong number using for loops (with example)
import java.util.*;
public class ArmstorngNumber {
public static void main(String args[]) {
int cube, num, quo, n;
int s = 0;
do
{
System.out.println("Enter Your Number");
Scanner sc = new Scanner(System.in);
num = sc.nextInt();//153
n = num;
for (int i = 0; i < 10; i++) {
int rem = num % 10;//3
quo = num / 10; //15
cube = rem * rem * rem;//9
s = s + cube;//0+9
num = quo;//0
}
System.out.println(s);
System.out.println(n);
if (s == n) {
System.out.println("The number is Armstrong");
System.out.println("-------------------------------------");
}
else {
System.out.println("The number is not Armstrong");
System.out.println("-------------------------------------");
}
}
while (n > 0);
}
}
Check the Armstrong number of any number [java] [Armstrong]
import java.util.*;
public class Armstrong {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("enter any number?");
int x = sc.nextInt();
int n=0;
int number = x;
int j =x;
int result = 0 ,remainder;
while (x!=0) {
x/=10;
++n;
}
for(;j>0 ;j=j/10) {
remainder=j%10;
result+=Math.pow(remainder, n);
}
if (number==result) {
System.out.print(number +" is Armstrong ");
}
else
System.out.print(number +" is not Armstrong");
}
}
here is my code, please check if this works for you!
import java.util.Scanner;
public class Armstromg {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Please enter the number: ");
int num = sc.nextInt();
int length = 0;
int temp1 = num;
while(temp1 != 0) {
temp1/=10;
length+=1;
}
int result = 1;
int temp2 = num;
for(int i = 1; i <= length; i++) {
temp2 = temp2 % 10;
result*=Math.pow(temp2,length);
}
if(result == num) {
System.out.print("The number is an armstrong number!");
} else {
System.out.print("The number is not an armstrong number");
}
}
}
package Loops;
public class ArmStrongNumber {
public static void main(String[] args) {
int digit1, digit2, digit3;
int number = 153;
int temp = number;
digit1 = number % 10;
number = number / 10;
digit2 = number % 10;
number = number / 10;
digit3 = number % 10;
if ((digit1 * digit1 * digit1) + (digit2 * digit2 * digit2) + (digit3 * digit3 * digit3) == temp) {
System.out.println(+temp + " Number is Armstrong ");
} else {
System.out.println("Number is not Armstrong");
}
}
}
//Not limited to 3 digit integers
public static void main(String[] args)
{
int num = 54748,a,sum=0;
int x = num;
int p =Integer.toString(num).length();
while (num !=0)
{
a = num%10;
num = num/10;
sum = sum + (int) Math.pow(a, p);
}
if (x==sum)
System.out.println("Its an Armstrong number");
else
System.out.println("Not an Armstrong number");
}
}
Scanner input = new Scanner (System.in);
int num , counter = 0 ,temp;
System.out.print("Enter Nmber :");
num = input.nextInt();
int lnum = num;
while ( num != 0 ){
num = num/10 ;
counter++;
}
int store_num_keyboard_input = lnum;
int new_tot = 0;
int c = counter;
while(lnum > 0){
temp = lnum % 10;
lnum = lnum / 10 ;
int m = 0; //m is counter
int tot = 1;
while (m != c){
tot = tot * temp;
m++;
}
new_tot = new_tot + tot;
}
System.out.println("new total "+ new_tot );
if(new_tot == store_num_keyboard_input){
System.out.println(store_num_keyboard_input + " is an Armstrong number" );
}
else{
System.out.println(store_num_keyboard_input + " is not an Armstrong number" );
}
My answer using JAVA 8
tested for..[1, 153, 370, 371, 407]
public class Armstrong {
public static boolean isArmstrong(int num) {
return num == getArmstrongSum(num);
}
public static int getArmstrongSum(int num) {
int pow = String.valueOf(num).length();
return IntStream.iterate(num, i -> i / 10)
.limit(pow)
.map(i -> (int) Math.pow(i % 10, 3))
.sum();
}
public static void main(String[] args) {
System.out.println(isArmstrong(153));
}
}
Thank you.
Im new to java and I was wondering how i would print prime palindrome without using strings and only methods.
This is what I have so far. I want to print every prime palindrome number before 50. I did this with prime numbers only and it was working but when I added in palindrome, it did not work.
EDIT: i added in the int original = number like one of the answers says but my output is always 2,3,5,7,11 and nothing more.
EDIT2(1 more question): I changed the value up to 1000 and my output is 2 3 5 7 11 313 353 373 383 727 757 787 797 919 929. The output is correct but isn't 101, 131, 151, 181, 191 also prime palindrome numbers? Why are they not included in the output?
public class primePalindrome {
public static void main (String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a number");
int num = input.nextInt();
System.out.println("The prime palindrome numbers are \n");
printPP(num);
}
public static void printPP(int numberOfPP) {
final int NUMBER_OF_PP_PER_LINE = 10;
int count = 0;
int number = 2;
while (number < numberOfPP) {
if(isPrime(number) && isPalindrome(number)) {
count++;
if (count % NUMBER_OF_PP_PER_LINE ==0) {
System.out.printf("%-5s\n", number);
}
else
System.out.printf("%-5s", number);
}
number++;
}
}
public static boolean isPrime(int number) {
for (int divisor = 2; divisor <= number / 2; divisor++) {
if (number % divisor == 0) {
return false;
}
}
return true;
}
public static boolean isPalindrome(int number) {
int reverse = 0;
int n = number;
for (int i = 0; i <= number; i++) {
int remain = number%10;
number = number/10;
reverse = reverse*10+remain;
}
if (reverse == n) {
return true;
}
}
return false;
}
}
There's only one 2-digit prime palindrome: 11. Every other 2-digit number is divisible by 11. Your output is thus correct.
Your isPalindrome is quite close:
1) Move the equality check outside the loop
2) Use while-loop. Using "for" results in omitting palindrome patterns 1X1, 2XX2 etc.
3) Dont't forget to preserve the argument:
public static boolean isPalindrome(int number) {
int original = number;
int reverse = 0;
while (number > 0) {
int digit = number%10;
number = number/10;
reverse = reverse*10+remain;
}
return reverse == original;
}
You were close. At the end you compare number to reverse. Unfortunately, number has been modified. You need to compare number's original value to reverse. Here's my modified version:
public static boolean isPalindrome(int number) {
int original = number;
int reverse = 0;
for (int i = 0; i <= number; i++) {
int remain = number % 10;
number = number / 10;
reverse = reverse * 10 + remain;
}
return reverse == original;
}
/* Palindrome Program In JAVA
Credit: Code Nirvana (www.codenirvana.in)
*/
import java.util.Scanner;
class Palindrome{
public static void main(String args[]){
System.out.print("Enter Number: ");
Scanner read = new Scanner(System.in);
int num = read.nextInt();
int n = num;
//reversing number
int rev=0,rmd;
while(num > 0)
{
rmd = num % 10;
rev = rev * 10 + rmd;
num = num / 10;
}
if(rev == n)
System.out.println(n+" is a Palindrome Number!");
else
System.out.println(n+" is not a Palindrome Number!");
}
}
Since most of the answers above doesn't work for both positive and negative numbers, following is one which works for negative numbers as well.
private static boolean isPalindrome(int n) {
int orignal = n, reversed = 0;
while (n != 0) {
reversed = (reversed * 10) + (n % 10);
n /= 10;
}
return reversed == orignal;
}
What if the given input is a huge number or a string?
I believe the below code should work for any input.
private boolean isPalindrome(String s) {
int lo = 0, hi = s.length()-1;
while(lo < hi) {
if(s.charAt(lo) == s.charAt(hi)) {
lo++; hi--;
} else {
return false;
}
}
return true;
}
import java.util.Scanner;
/*if given number is same with reverse number
then this number is called as Palindrome number. */
public class PalindromeNumber {
public static void main(String args[])
{
int input,store,output=0;
Scanner in=new Scanner(System.in);
System.out.println("Enter a number for check.");
input=in.nextInt();
store=input;
while (input!=0)
{
output=output*10;
output=output+input%10;
input=input/10;
}
System.out.println(output);
if (output == store)
{
System.out.println("This is a palindrome number.");
}
else
{
System.out.println("This is not a palindrome number.");
}
in.close();
}
}
import java.util.*;
/*
# Author 12CSE54
# Date 29.10.14
*/
public class cpalindrome
{
public static void main(String ar[])throws Exception
{
Scanner s=new Scanner(System.in);
System.out.println("Enter the number\n");
int n=sc.nextInt();
int s=0,r;
while(n>0)
{
r=n%10;
s=(s*10)+r;
n/=10;
}
if(n==s)
System.out.println("palindrome\n");
else
System.out.println("not a palindrome");
}
}
import java.util.*;
public class PalPrime
{
public boolean prime(int n)
{
int c=0;
for(int i=1;i<=n;i++)
{
if(n%i==0)
c++;
}
if(c==2)
return true;
else
return false;
}
public boolean palindrome(int n)
{
int rev=0,temp=n;
while(temp!=0)
{
rev=rev*10+(temp%10);
temp=temp/10;
}
if(rev==n)
return true;
else
return false;
}
public static void main(String args[])
{
Scanner ob=new Scanner(System.in);
System.out.println("Enter number to be checked");
int num=ob.nextInt();
PalPrime obj=new PalPrime();
if(obj.prime(num)==true && obj.palindrome(num)==true)
System.out.println(num+" is a Prime Palindrome i.e. a PalPrime Number");
else
System.out.println(num+" is not a PalPrime Number");
}
}
TRY THIS!
This is easy to Understand
public class StringDemo {
public static void main(String args[]) {
if(palindrome("1211")){
System.out.println("Yes IT IS palindrome");
}
if(palindrome("121")){
System.out.println("Yes IT IS palindrome");
}
}
public static boolean palindrome(Object o){
String s=(String)o;
boolean result=true;
int temp=s.length()-1;
for(int c=0;c<temp;c++){
if(s.charAt(c)==s.charAt(temp)){
temp--;
//System.out.println("Pallidrom start "+ s.charAt(c));
//System.out.println("Pallidrom end "+ s.charAt(temp));
}else{
System.out.println("NOT palindrome");
return false;
}
}
return result;
}
}
Result is