Modified Kaprekar Numbers Hackerrank Solution - java
For explanation watch video :
Code::
import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.function.*;
import java.util.regex.*;
import java.util.stream.*;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toList;
class Result {
/*
* Complete the 'kaprekarNumbers' function below.
*
* The function accepts following parameters:
* 1. INTEGER p
* 2. INTEGER q
*/
public static void kaprekarNumbers(int p, int q) {
ArrayList<Long> al = new ArrayList<>();
for(long i=p;i<=q;i++){
long sq = i*i;
String num = String.valueOf(i);
String s = String.valueOf(sq);
int leftLength = s.length() - num.length();
long leftNum = 0;
if(leftLength == 0){
leftNum = 0;
}else{
leftNum = Long.parseLong(s.substring(0,leftLength));
}
long rightNum = Long.parseLong(s.substring(leftLength));
long sum = leftNum + rightNum;
if(sum==i){
al.add(i);
}
}
if(al.size()==0){
System.out.println("INVALID RANGE");
}else{
for(int i=0;i<al.size();i++){
System.out.print(al.get(i)+" ");
}
}
}
}
public class Solution {
public static void main(String[] args) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
int p = Integer.parseInt(bufferedReader.readLine().trim());
int q = Integer.parseInt(bufferedReader.readLine().trim());
Result.kaprekarNumbers(p, q);
bufferedReader.close();
}
}
Comments
Post a Comment