Hackerrank - UNIQUE ARMSTRONG NUMBER

Consider a non-empty array Inarr of unique elements such as satisfies the following condition 0

  • Starting from the leftmost element in inarr, for each element
  • Form all possible numbers by concatenating pair of elements in inarr such that the second element of the pair appears after the first element in inarr.
  • From the numbers formed, find and add the unique Armstrong numbers) outarr in the order of occurrence of elements in inarr.
  • If two pairs have the same first number, then consider the order of occurrence of second elements in the pairs
  • An Armstrong number is equal the sum of its own digits each raised to the power of the number of digits in the number
  • If there is no Armstrong number found, print-1 as output

Input Format

First line contains inarr, with the elements separated by ‘,’ (comma)

Constraints

Read the inputs from the standard input stream

Output Format

Print outarr, with the elements separated by ',' (comma) to the standard output stream

Sample Input 0

15,3,1,70,53,71

Sample Output 0

153,370,371




import java.util.*;

public class ArmStrong {
private static Integer[] getDigits(String[] innarrStr) {
ArrayList<Integer> digits = new ArrayList<Integer>();
for (int i = 0; i < innarrStr.length-1; i++) {
for (int j = i+1; j < innarrStr.length; j++) {
digits.add(Integer.parseInt(innarrStr[i]+innarrStr[j]));
}
}
return digits.toArray(new Integer[0]);
}

private static boolean isArmStrong(Integer integer) {

int squaredSum = 0;
int temp = integer;
while(temp > 0)
{
int rem = temp%10;
squaredSum += rem * rem * rem;
temp /= 10;
}
// System.out.println("for "+d[j]+" "+sum);
if (squaredSum == integer)
{
return true;
}else{
return false;
}

}
private static Integer[] getArmstrongDigits(Integer[] innarr) {
ArrayList<Integer> armsDig = new ArrayList<Integer>();
for (int i = 0; i < innarr.length; i++) {
if(isArmStrong(innarr[i])){
armsDig.add(innarr[i]);
}
}

ArrayList<Integer> armsDigUnique = new ArrayList<Integer>();

for (int i = 0; i < armsDig.size(); i++) {
if (!armsDigUnique.contains(armsDig.get(i))){
armsDigUnique.add(armsDig.get(i));
}
}
return armsDigUnique.toArray(new Integer[0]);
}


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String innarrStr[] = sc.nextLine().split(",");
Integer innarr[] = getDigits(innarrStr);
Integer armsarr[] =getArmstrongDigits(innarr);

if(armsarr.length == 0){
System.out.println(-1);
}else {
String res = Arrays.toString(armsarr);
res = res.substring(1,res.length()-1);
res = res.replace(", ",",");
System.out.println(res);
}
}





}

 

Comments

Popular posts from this blog

Hackerrank - Quicksort 2 - Sorting