Monday 30 September 2013

Program to check the difference b/w the highest number and lowest number(formed by digits in givenNumber) is equal to given number or not ? if not, choose the difference result as the new input and repeat the process untill the difference equals given number

//java code -- to understand this you need to have little knowledge on Collections interface and ArrayList class, can be found in java.util package
Here am giving two solutions with recursion and without recursion

//with recursion

import java.util.*;
class Calculation
{

static int findHighestOrLeast(int num,boolean highOrLow)   //true - highest and false - least
{
List<Integer> l = new ArrayList<Integer>();
while( num > 0 )
{
l.add(num%10);
num /= 10;
}
Collections.sort(l);
if(highOrLow)
Collections.reverse(l);
num = 0;
for(int i : l )
num = num*10 + i;
return num;

}
static int findNumber(int num)
{
int num2=0;

num2 = findHighestOrLeast(num,true) - findHighestOrLeast(num,false);
if(num == num2)
{
return num;
}
else
{
return findNumber(num2);
}
}
public static void main(String[] args)
{
int num1 = 7624;
System.out.println(findNumber(num1));
}
}

//without recursion

import java.util.*;
class Calculation
{
static int leastPossibleNumber(int num)
{
List<Integer> l = new ArrayList<Integer>();
while( num > 0 )
{
l.add(num%10);
num /= 10;
}
Collections.sort(l);
num = 0;
for(int i : l )
num = num*10 + i;
return num;
}
static int highestPossibleNumber(int num)
{
List<Integer> l = new ArrayList<Integer>();
while( num > 0 )
{
l.add(num%10);
num /= 10;
}
Collections.sort(l);
Collections.reverse(l);
num = 0;
for(int i : l )
num = num*10 + i;
return num;
}
public static void main(String[] args)
{
int num1 = 7624;
int num2=0;
while( true )
{
num2 = highestPossibleNumber(num1) - leastPossibleNumber(num1);
if(num1 == num2)
{
System.out.println(num1 + "  " + num2);
break;
}
else
{
num1 = num2;
}
}
}
}

instead of having two methods leastPossibleNumber and highestPossibleNumber, we can have one method findLeastOrHighest with an extra boolean argument. if you are keen about reusability then you can plan that way.

1 comment:

  1. I would highly recommend to go through this program. it is one of good programs i come across

    ReplyDelete