fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6.  
  7. /* Name of the class has to be "Main" only if the class is public. */
  8. class Ideone
  9. {
  10. private static int calc(int number) {
  11. // edge case
  12. if (number == 0) {
  13. return 1;
  14. }
  15.  
  16. int[] digitCount = new int[10];
  17. int[] digitFactorial = new int[10];
  18. int maxDigit = 0;
  19. int result = 0;
  20. int runNumber = number;
  21.  
  22. // convert number to digit counters
  23. while(runNumber > 0) {
  24. int digit = runNumber % 10;
  25. digitCount[digit]++;
  26. if (maxDigit < digit) {
  27. maxDigit = digit;
  28. }
  29. runNumber /= 10;
  30. }
  31.  
  32. // calculate required factorials
  33. digitFactorial[0] = 1;
  34. for(int i=1; i <= maxDigit; i++) {
  35. digitFactorial[i] = digitFactorial[i-1] * i;
  36. }
  37.  
  38. // calculate sum
  39. for(int i=0; i <= maxDigit; i++) {
  40. result += (digitFactorial[i] * digitCount[i]);
  41. }
  42.  
  43. // debug
  44. //System.out.printf("Number: %d, Factorials: %s, Counts: %s%n", number,
  45. // Arrays.toString(digitFactorial),
  46. // Arrays.toString(digitCount));
  47.  
  48. return result;
  49. }
  50.  
  51. private static void test(int testId, int number, int expectedValue) {
  52. int result = calc(number);
  53. if (result == expectedValue) {
  54. System.out.printf("Test %d: OK%n", testId);
  55. } else {
  56. System.out.printf("Test %d: failed, expected %d, result %d%n", testId, expectedValue, result);
  57. }
  58. }
  59.  
  60. public static void main (String[] args) throws java.lang.Exception
  61. {
  62. test(1, 0, 1);
  63. test(2, 1, 1);
  64. test(3, 101, 3);
  65. test(4, 2, 2);
  66. test(5, 3, 6);
  67. test(6, 4, 24);
  68. test(7, 9, 362880);
  69. test(8, 91, 362880+1);
  70. test(9, 912, 362880+1+2);
  71. }
  72. }
Success #stdin #stdout 0.07s 34144KB
stdin
Standard input is empty
stdout
Test 1: OK
Test 2: OK
Test 3: OK
Test 4: OK
Test 5: OK
Test 6: OK
Test 7: OK
Test 8: OK
Test 9: OK