Advertisement
Guest User

Untitled

a guest
Feb 13th, 2016
55
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.86 KB | None | 0 0
  1. public class HappyNumberCounter {
  2.  
  3. public static int getLastDigit(final long number) {
  4. return Math.toIntExact(number % 10);
  5. }
  6.  
  7. public static long digitSquareSumCalculator(final long number) {
  8. int remainder = getLastDigit(number);
  9. long quotient = number / 10;
  10. long digitSum = remainder * remainder;
  11. while (quotient > 0) {
  12. remainder = getLastDigit(quotient);
  13. quotient = quotient / 10;
  14. digitSum = remainder * remainder;
  15. }
  16.  
  17. return digitSum;
  18. }
  19.  
  20. public static long countHappyNumbersInRange(final long startInclusive, final long endInclusive) {
  21. final Map<Long, Boolean> happyNumbers = new HashMap<>();
  22. long count = 0;
  23. for (long index = startInclusive; index <= endInclusive; index++) {
  24. long number = index;
  25.  
  26. // case 1: already been cached
  27. // case 2: has not been cached
  28. // case 3: has not been cached but starts with 1 or 4
  29. // case 4: has not been cached and does not start with 1 or 4
  30.  
  31. Boolean isHappy = happyNumbers.get(number);
  32. if (isHappy == Boolean.TRUE) {
  33. count++;
  34. } else if (isHappy == null) {
  35. long lastDigit = getLastDigit(number);
  36. if (lastDigit == 1) {
  37. happyNumbers.put(number, Boolean.TRUE);
  38. count++;
  39. } else if (lastDigit == 4) {
  40. happyNumbers.put(number, Boolean.FALSE);
  41. } else {
  42. final List<Long> numbers = new ArrayList<>();
  43. while (lastDigit != 1 && lastDigit != 4 && isHappy == null) {
  44. numbers.add(number);
  45. number = digitSquareSumCalculator(number);
  46. isHappy = happyNumbers.get(number);
  47. lastDigit = getLastDigit(number);
  48. }
  49.  
  50. for (final Long num : numbers) {
  51. happyNumbers.put(num, isHappy);
  52. }
  53.  
  54. if (isHappy) {
  55. count++;
  56. }
  57. }
  58. }
  59. }
  60. return count;
  61. }
  62.  
  63. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement