Problem:
TopCoder Problem Statement - DivisorDigits
Overview:
Determine which digits in a number evenly divide the number.
Java Source:
01: /* 02: TopCoder 03: Single Round Match: 148 04: Division: 2 05: Level: 1 06: Points: 250 07: 08: Single Round Match 215 09: Division: 2 10: Level: 1 11: Points: 250 12: 13: Description: http://community.topcoder.com/stat?c=problem_statement&pm=1741 14: */ 15: 16: public class DivisorDigits { 17: 18: public int howMany(int number) { 19: 20: int count = 0; 21: 22: // Convert the number parameter into a char array 23: char[] digits = new String("" + number).toCharArray(); 24: 25: // Test each digit to see if it evenly divides number 26: for (char c : digits) { 27: 28: // Convert the character into an int 29: int i = Integer.valueOf(c) - '0'; 30: 31: // Don't try to divide by 0. 32: if (i == 0) { continue }; 33: 34: if ((number % i) == 0) { 35: count++; 36: } 37: } 38: 39: return count; 40: } 41: }
Notes:
On line 23, we convert the "number" parameter into a char array. This makes it easy for us to iterate through each digit. Line 26 handles the iteration, and line 29 converts each of the chars into an int. Be careful here to subtract off the value of '0' - otherwise your digit will be 48 greater than you expect!
Then, it's just a matter of seeing if the digit divides the number evenly. This is done on line 34 using the mod operator %.
No comments:
Post a Comment