HackerRank.com “Find Digits”

Here is a problem from hackerrank that invovles splitting apart a number and performing division on the original. I solved this one on the fly so the video has a few mistakes but the end solution works! I also changed how to convert a string “1” number to an int 1.

HackerRank.com FindDigits

import java.io.PrintWriter;
import java.util.Scanner;

public class Solution {

	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);

		//validate test case count
		int T = in.nextInt();
		if (1 > T || T > 15) {
			in.close();
			return;
		}

		//start work on each test case
		for (int i = 0; i < T; i++) {

                       //validate that the number is in range
                       int N = in.nextInt();
                       int limit = (int) Math.pow(10, 9);
                       if (0 >= N || N >= limit) {
				in.close();
				return;
			}

			int acc = 0;

			//different from video
			String digitString = "" + Integer.toString(N);
			char[] digits = digitString.toCharArray();

			//perform loop over the digit string
			for (int j = 0; j < digits.length; j++) {
				if (digits[j] != '0') {
					int digit = Integer.parseInt("" + digits[j]);
					if (N % digit == 0) {
						acc++;
					}
				}
			}

			System.out.println("" + acc);
		}

		in.close();
	}
}

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Subscribe to Blog via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 2 other subscribers