HackerRank : Week of Code 26 – Best Divisor

By | November 30, 2016
Best Divisor:

Kristen loves playing with and comparing numbers. She thinks that if she takes two different positive numbers, the one whose digits sum to a larger number is better than the other. If the sum of digits is equal for both numbers, then she thinks the smaller number is better. For example, Kristen thinks that 13 is better than 31 and that 12 is better than 11 .

Given an integer,n , can you find the divisor of n that Kristin will consider to be the best?

Input Format

A single integer denoting .


 0<n< 10^5

Output Format

Print an integer denoting the best divisor of .

Sample Input 0


Sample Output 0


Explanation 0

The set of divisors of 12 can be expressed as {1,2,3,4,6,12}. The divisor whose digits sum to the largest number is 6 (which, having only one digit, sums to itself). Thus, we print 6 as our answer.


In my approach, I have calculated all the factors of input number.

I have stored the factors in a HashMap along with the sum of its digits as value.
While storing the key and values in map I kept calculating the max value which 
is being inserted in map during all insertions.

Then I traversed the map and if the value is equal to max value then I have 
stored the values in a treeset. 
And finally displayed the first value of treeSet ( which is answer ).

You can directly use treemap to store key and values. That way you can 
just find the first occurrence of max value and print it. You will not need
Set in this case.

Code :

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Scanner;
import java.util.Set;
import java.util.TreeSet;

public class BestDivisor {
	public static int sumDig(int digit)
		int summm=0;
		return summm;
	public static void main(String[] args) {
		Scanner scan= new Scanner(System.in);
		Map<Integer,Integer> mapDigits=  new HashMap<Integer, Integer>();
		int n=scan.nextInt();
		int maxVal=0;
		for(int i=1;i<=n;i++) { if(n%i==0) { int digSum=sumDig(i); mapDigits.put(i,digSum); if(digSum>maxVal)
		SetmySet= new TreeSet();
		for (Entry<Integer,Integer> integer : mapDigits.entrySet()) 
			int val=integer.getValue();
			for (Integer integer : mySet) {