The Tiny Miny Smallest Number
Problem: You are given A and B . You have to calculate A^1 , A^2 , A^3... A^B , append result.
Find a permutation of outcome which leads to minimum Result
Example
9 3
9^1 = 9
9^2 = 81
9^3 = 729
9^4 = 6561
9 81 729 6561
We get 9817296561
Smallest Permutation : 1125667899
We know that a number will lie from 1 to 9 , hence we can use hash to count occurrence of a number and in return print it.
Idea is to find all power and store them into hash
Code:
public static void addIntoHash(int hash[],double num)
{
while(num>0)
{
int rem=(int)num%10;
++hash[rem];
num/=10;
}
}
public static StringBuilder fn(int a,int n)
{
int hash[]=new int[10];
StringBuilder res=new StringBuilder();
while(n-- >0)
{
double num=Math.pow(a,n+1);
addIntoHash(hash,num);
}
for(int i=1;i<=9;++i)
{
while(hash[i]>0)
{res.append(i);
--hash[i];
}
}
return res;
}
public static void main (String[] args)
{
Scanner ab=new Scanner(System.in);
int a=ab.nextInt();
int n=ab.nextInt();
System.out.println(fn(a,n));
}
Find a permutation of outcome which leads to minimum Result
Example
9 3
9^1 = 9
9^2 = 81
9^3 = 729
9^4 = 6561
9 81 729 6561
We get 9817296561
Smallest Permutation : 1125667899
We know that a number will lie from 1 to 9 , hence we can use hash to count occurrence of a number and in return print it.
Idea is to find all power and store them into hash
Code:
public static void addIntoHash(int hash[],double num)
{
while(num>0)
{
int rem=(int)num%10;
++hash[rem];
num/=10;
}
}
public static StringBuilder fn(int a,int n)
{
int hash[]=new int[10];
StringBuilder res=new StringBuilder();
while(n-- >0)
{
double num=Math.pow(a,n+1);
addIntoHash(hash,num);
}
for(int i=1;i<=9;++i)
{
while(hash[i]>0)
{res.append(i);
--hash[i];
}
}
return res;
}
public static void main (String[] args)
{
Scanner ab=new Scanner(System.in);
int a=ab.nextInt();
int n=ab.nextInt();
System.out.println(fn(a,n));
}
0 Comments:
Post a Comment