Guest User

Untitled

a guest
Nov 18th, 2018
98
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.17 KB | None | 0 0
  1. package com.abhishek.dojo;
  2.  
  3. import java.util.HashSet;
  4.  
  5. /*Write an algorithm to determine if a number is "happy".
  6.  
  7. A happy number is a number defined by the following process:
  8. Starting with any positive integer, replace the number by the sum of
  9. the squares of its digits, and repeat the process until the number
  10. equals 1 (where it will stay), or it loops endlessly in a cycle
  11. which does not include 1. Those numbers for which this process ends
  12. in 1 are happy numbers.
  13.  
  14. Example:
  15.  
  16. Input: 19
  17. Output: true
  18. Explanation:
  19. 12 + 92 = 82
  20. 82 + 22 = 68
  21. 62 + 82 = 100
  22. 12 + 02 + 02 = 1
  23. */
  24.  
  25. class FindHappyNumber {
  26. public boolean isHappy(int n) {
  27. HashSet<Integer> set = new HashSet<Integer>();
  28. // loop will terminate once we start seeing original number cycle again
  29. while (!set.contains(n)){
  30. set.add(n);
  31. n = getSum(n);
  32. if(n == 1){
  33. return true;
  34. }
  35. }
  36. return false;
  37. }
  38.  
  39. //quick way to get of squares of a number
  40. public int getSum(int n){
  41. int sum =0;
  42. while (n>0){
  43. sum += (n%10) * (n%10);
  44. n = n/10;
  45. }
  46. return sum;
  47. }
  48. }
Add Comment
Please, Sign In to add comment