Peters Number Code solution in Java
Peters Number solution in Java
Imagine
there is a person who likes numbers a lot and wants to choose a number that
consists of n digits.But it has to be special. The person also wants it to have
a sum of digits equal to s,which should be as large as possible .The number
cannot have leading 0s.Can you help the person find that number or determine
that it doesn’t exist.
Input:
The first
line of input contains an integer n, representing the number of digits in the
requested number ,The second line of input contains s,representing sum of digits
Output:
Print the
requested number if it exists or -1 otherwise
Example1:
Input:
1
5
Output:
5
Example
2:
Input:
2
15
Output
96
Code in Java
import java.util.Scanner;
public class Peterscode {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner
sc = new Scanner(System.in);
int n = sc.nextInt();
int sumed =sc.nextInt();
sc.close();
System.out.println(peters(n,sumed));
}
static int peters(int n,int sumed)
{
if(Integer.toString(sumed).length()==1)
{
for(int i=0;i<9;i++)
{
if(i==sumed)
{
return i;
}
}
}
else if(Integer.toString(sumed).length()>1)
{
String
op="";
if(9*n<sumed)
{
return -1;
}
else
{
for(int i=0;i<9;i++)
{
if(9*i<sumed)
{
if(sumed-(9*i)<9)
{
op="9".repeat(i);
op=op+Integer.toString(sumed-(9*i));
}
}
}
return Integer.parseInt(op);
}
}
return n;
}
}
Comments
Post a Comment