Square With one's


Square With One's


/*
 * WAP which inputs an integer N. Output the square of the smallest number M
 * containing N number of 1’s. You may use strings to store results.
 * Example:
 *
 * N=2
 * Output: 121
 *
 * N<=6
 */

public class hackerearth3 {

public static void main(String[] args) {

hackerearth3 h3=new hackerearth3();
System.out.println(h3.displayOutput(1));

}

public int displayOutput(int n) {
int count=1;
int output=0;
for(int i=1;i==count;i++)
{
int square=i*i;
if(check_N_ones(n,square))
{
output=square;
break;
}
else
count++;
}
return output;
}

private boolean check_N_ones(int n,int square) {
int count=0;
String g=square+"";
for (int i = 0; i < g.length(); i++) {
if(g.charAt(i)=='1') {
count++;
}
}
if(count==n)
return true;
else
return false;
}

}

Comments