Java code for finding the next palindrome - Error in output - java

The problem is to find the smallest palindrome integer after the given number.
Input the number of integers i.e test cases.
Input the integers in an array.
Output: The next palindrome integer corresponding to each integer in the array respectively.
There are various methods to solve this problem(many solutions on SO as well), but I cannot figure out why I can't get the output from this code. From running the code many times, I have concluded that if any test case needs more than 1 increment to become a palindrome, the program goes into an infinite loop somehow.
Eg. If I input 100 as a test case, the output is 101.Similarly, if I enter 908, I get 909 as output. But if I enter 108, I do not get 111 as the output.
Please bear with my silly mistakes, I'm new to coding in Java. Thanks
import java.util.Scanner;
class nextPalindrome {
public static void nextPalindromeGenerate(int n)
{
int flag=1;
int digit; //to store the mod value
int rev=0; //reverse of the number
int original; //dummy to store the original number
if(n<10)
{ System.out.println(n+1); //If number is single digit, next smallest palindrome is n+1
flag=0;
}
while(flag!=0)
{ ++n;
original=n;
while(n>0) //loop for reversing the number
{
digit=n%10;
rev=rev*10+digit;
n=n/10;
}
if(rev==original) //check if original equals the reverse(original)
{
System.out.println(rev);
flag=0;
}
else flag=1;
}
}
public static void main(String[] args)
{
#SuppressWarnings("resource")
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int[] palinList=new int[n];
for(int i=0;i<n;i++)
{
palinList[i]=sc.nextInt();;
}
for(int j=0;j<n;j++)
{
nextPalindromeGenerate(palinList[j]);
}
}
}

You increment n to the next integer to test for being palindromic(!), save it in origingal, then trash n to see if it is a palindrome. But you never reset n for the next iteration.

The problem was extremely trivial, merely resetting rev, digit and n to meaningful values. The working program is as follows :
import java.util.Scanner;
class nextPalindrome {
public static void nextPalindromeGenerate(int n)
{
int flag=1;
int digit; //to store the mod value
int rev=0; //reverse of the number
int original; //dummy to store the original number
if(n<10)
{ System.out.println(n+1); //If number is single digit, next smallest palindrome is n+1
flag=0;
}
original=n;
while(flag!=0)
{ rev=0;digit=0;
n=++original;
while(n>0) //loop for reversing the number
{
digit=n%10;
rev=rev*10+digit;
n=n/10;
}
if(rev==original) //check if original equals the reverse(original)
{
System.out.println(original);
flag=0;
}
else flag=1;
}
}
public static void main(String[] args)
{
#SuppressWarnings("resource")
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int[] palinList=new int[n];
for(int i=0;i<n;i++)
{
palinList[i]=sc.nextInt();;
}
for(int j=0;j<n;j++)
{
nextPalindromeGenerate(palinList[j]);
}
}
}

Related

are Print Statements inside or outside of For Loops?

I'm coding a program to calculate factorials but can't seem to figure out the part where it actually prints out the final value.
import java.util.*;
public class Factorial {
public static void main(String[] args) {
Scanner scan=new Scanner(System.in);
System.out.println("Enter integer value: ");
int x=scan.nextInt();
System.out.print(x+"!=");
int y=0;
for(int i=x;i>0;i--) {
//y=x*i;
y=i*(i-1);
if(i==1)
System.out.print(i+"=");
else
System.out.print(i+"*");
//for (int j=2;j>=1
}
System.out.print(y);
}
}
the program is supposed to display the numbers it multiplied by as well
i.e. INPUT=5
OUTPUT= 5!=5*4*3*2*1=120
or
OUTPUT=5!=1*2*3*4*5=120
First thing you need to do is to put the curly brackets on and then indent,so as to decrease the confusion.
The code below does what you intend to and has the necessary comments
import java.util.*;
public class Factorial {
public static void main(String[] args) {
Scanner scan=new Scanner(System.in);
System.out.println("Enter integer value: ");
int x=scan.nextInt();
System.out.print(x+"!=");
int y=1;// Initialize to 1 not 0 as you'll be multiplying.
for(int i=x;i>0;i--) {
/*
Iteration by iteration:
i = 5,y= 1-> y = 1*5
i = 4,y= 5-> y = 5*4
So on...
*/
y*=(i);
if(i==1)
{
// Print Equal only if its the last number. Since
we are going 5*4*3*2*1 =. We need this if to print
1 =.
System.out.print(i+"=");
}
else
{
//For other cases just print Number and *.
System.out.print(i+"*");
}
}
// Print the actual output.
System.out.print(y);
}
}

Keep Reversing the no. & adding it to the original no. until there is a Palindrome Number

It's not "Find the Palindrome of a Number" ! it's a bit twisted than that:
Step 1: Reverse the digits of a original number.
Step 2: Add the reversed number.
Step 3: If the new number is a palindrome number then print the output.
The limit is 15 steps & we can print the original number if that is a palindrome in itself. We have to use function calling in this program. Here I have used two functions() - FIRST to reverse the number & SECOND to add the original number and the reversed number & check if the sum is a Palindrome or not.
Please suggest your opinions if I can improve this long code in any way.
PS: newbie in Java & especially function calling!
Thank you!! Here's the code, it's a little bit long! I am sorry :(
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
}
}
}
The problem is in your PalinReverse method. Your while loop is running infinitely because the condition is always true.
Replace
while (n>0)
with
while (n1>0)
You should also learn how to debug a program. Your life will be 10 times easy after that.

Output for finding kth digit from right of a^b does not come as Expected?

Given two numbers a and b, find kth digit from right of a^b?
Link for the problem:
http://www.practice.geeksforgeeks.org/problem-page.php?pid=302
MyApproach:
I took 4 numbers as Input.First was the number of test cases.Then,Input was numbers a b and k respectively(Seperated by space).I calculated a^b and then from right searched each number till the time kth digit is not equal to the count.If I get them equal I returned the remainder expected.
Below is the Code:
public static void main (String[] args)
{
Scanner sc=new Scanner(System.in);
int T=sc.nextInt();
for(int i=1;i<=T;i++)
{
int count=1;
int a=sc.nextInt();
System.out.print(" ");
int b=sc.nextInt();
System.out.print(" ");
int k=sc.nextInt();
long result=(long) Math.pow(a,b);
if(k!=count)
{
while(k!=count)
{
count++;
int remainder=(int) (result%10);
result=result/10;
}
}
result=result%10;
System.out.println(result);
}
}
GeeksId Output:
Wrong !! Here your code Failed
Input:
7 6 3
And its Correct output is:
6
Eclipse ID:
Input:
7 6 3
Output
6
Wny I am getting Failed on geeksId?Is my solution do not produce correct output?
It seems like you did not follow the direction of the problem. The problem gives you a few constraints. you do not do a check for those. You should add the code to check that, so it will make sure you do not run into any exceptions.
I wanted to point out that you can just convert the Math.pow(a,b) result to string, and print the length - k char using the charAt function. This will make it very easy. and gets rid of the loops.
Code for that part is:
String tempString = String.valueOf(result);
System.out.println(tempString.charAt(tempString.length() - k));
Hope this puts you in the right direction.
Can also be done this way without much String operations and not expecting the intermediate output a^b to store in long data type,
private void handle() {
Scanner scanner = new Scanner(System.in);
int T = scanner.nextInt();
for(int i = 0; i < T; i++) {
findKthDigit(scanner);
}
scanner.close();
}
private void findKthDigit(Scanner scanner) {
int a = scanner.nextInt();
int b = scanner.nextInt();
int k = scanner.nextInt();
System.out.println((int)((Math.pow(a, b) % Math.pow(10, k))
/ Math.pow(10, k-1)));
}
As requested, your program is modified to make it work in GFG system,
public static void main (String[] args)
{
Scanner sc=new Scanner(System.in);
int T=sc.nextInt();
for(int i=1;i<=T;i++)
{
int count=1;
int a=sc.nextInt();
//System.out.print(" ");
int b=sc.nextInt();
// System.out.print(" ");
int k=sc.nextInt();
long result=(long) Math.pow(a,b);
if(k!=count)
{
while(k!=count)
{
count++;
int remainder=(int) (result%10);
result=result/10;
}
}
result=result%10;
System.out.println(result);
}
}
Hope this helps to understand. (however, you need to check other related exceptions for a good programming practice)

comparision b/w elements of an array

in this code i want to take no. of testcases by keyboard input and rest is the same problem. only what i am doing is like. if i take 2 test cases then it shud be print the result based on both cases after taking the complete input. For example: INPUT testcases : 2 //case1// 5(no of building) 7 5 2 11 1 //case2// 3(no. of building) 1 2 3 OUTPUT 7//OUTPUT FOR 1ST CASE// 0//OUTPUT FOR 2ND CASE// HOPE, NOW PROBLEM IS CLEAR
import java.util.Scanner;
public class Komal {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
System.out.println("enter the test cases");
int T=sc.nextInt();
for(int i=1;i<=T;i++)
{
System.out.println("total no of building");
int n=sc.nextInt();
int ar[]=new int[n];
for(int j=0;j<n;j++)
{
System.out.println("enter the heights");
ar[j]=sc.nextInt();
}
for(int j=1;j<ar.length;j++)
{int sum=0;
if(ar[0]<ar[i])
{
break;
}else
{
sum += (ar[0]-ar[i]);
}
System.out.println(sum);
}
}
}
}
Here is the complete code. Luckily i had my laptop running and this isn't a very difficult program.
public class TillGreater{
public static void main(String args[]){
int[] ar = {5,4,2,7,1};
int sum=0;
for(int i = 1 ; i < ar.length;i++){
if(ar[0]<ar[i]){
break;
}else{
sum = sum + (ar[0]-ar[i]);
}
}
System.out.println(sum);
}
}
try this:
public static int SumUntilBigger(int[] a)
{
int sum=0;
for(int i=1;i<a.length;i++)
{
if(a[i]<=a[0])
sum+=a[0]-a[i];
else
return sum;
}
return sum;//will reach this statement if all the elements are bigger than the first one
}
this compares each element with the first element and when the element is bigger it just return the sum and exits from method, if all elements are bigger than the first one just return the sum of all differences.
you can use it in main like this:
public static void main(String[] args)
{
Scanner s=new Scanner(System.in);
System.out.println("enter the size of the array");
int size=s.nextInt();
int[] a=new int[size];
System.out.println("enter the array values");
for(int i=0;i<size;i++)
a[i]=s.nextInt();
System.out.println("The differences sum : "+SumUntilBigger(a));
}

How to extract the maximum number using bubble sort in java?

I am a beginner in java and I have a problem in finding the maximum number in an integer array using bubble sort
This is how my Program is:
import java.util.Scanner;
class Bubblesorting
{
Scanner sc=new Scanner(System.in);
void ascendingOrder()
{
int[] no=new int[10];
System.out.println("ENTER 10 NUMBERS");
for(int i=0;i<no.length;i++)
{
no[i]=sc.nextInt();
for(int j=0;j<no.length;j++)
{
for(int k=j;k<no.length-1;k++)
{
if(no[j]<no[k+1])
{
int t=no[k+1];
no[k+1]=no[j];
no[j]=t;
}
}
}
}
System.out.println(no[no.length]);
}
}
You don't need to sort an array in order to get the maximum number in it. Simply iterate once over the array updating the maximum value found so far. Something like:
import java.util.Scanner;
class Bubblesorting
{
Scanner sc=new Scanner(System.in);
void ascendingOrder()
{
int[] no=new int[10];
System.out.println("ENTER 10 NUMBERS");
for(int i=0;i<no.length;i++)
{
no[i]=sc.nextInt();
}
int maxv = no[0];
for (int i =0;i<10;++i) {
if (no[i] > maxv) {
maxv = no[i];
}
}
System.out.println(maxv);
}
}
Still if you insist that you have to sort the array first - separate the read from the sorting logic. You should first read all the numbers and then sort the whole array. Also keep in mind arrays in most programming languages are 0 indexed thus valid indices for no are 0 to no.length-1 so you should System.out.println(no[no.length - 1]); instead of System.out.println(no[no.length]);.
Your if condition should be check greater then condition like if(no[j]>no[k+1]).
And also do change in sysout
System.out.println(no[no.length-1]);
Your code should something like
Scanner sc=new Scanner(System.in);
void ascendingOrder()
{
int[] no=new int[10];
System.out.println("ENTER 10 NUMBERS");
for(int i=0;i<no.length;i++)
{
no[i]=sc.nextInt();
for(int j=0;j<no.length;j++)
{
for(int k=j;k<no.length-1;k++)
{
if(no[j]>no[k+1])
{
int t=no[k+1];
no[k+1]=no[j];
no[j]=t;
}
}
}
}
System.out.println(no[no.length-1]);
}

Categories

Resources