Created
April 22, 2016 00:00
-
-
Save booknara/f50ab3136d116802b16fdec86e7d93bd to your computer and use it in GitHub Desktop.
Checking Happy number
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.HashSet; | |
import java.util.Set; | |
/** | |
* Happy number (https://en.wikipedia.org/wiki/Happy_number) : A happy number is a number defined by the following process: | |
* Starting with any positive integer, replace the number by the sum of the squares of its digits, | |
* and repeat the process until the number either equals 1 (where it will stay), | |
* or it loops endlessly in a cycle which does not include 1. | |
* Those numbers for which this process ends in 1 are happy numbers, | |
* while those that do not end in 1 are unhappy numbers (or sad numbers). | |
* Created by Daehee Han(@daniel_booknara) on 4/21/16. | |
*/ | |
public class HappyNumber { | |
public static void main(String[] args) { | |
int value = 31; | |
if (isHappyNumber(value)) | |
System.out.println("Happy"); | |
else | |
System.out.println("Not happy"); | |
} | |
public static boolean isHappyNumber(int n) { | |
Set<Integer> set = new HashSet<>(); | |
while (set.add(n)) { | |
int sum = 0; | |
while(n != 0) { | |
int digit = n % 10; | |
n = n / 10; | |
sum += digit * digit; | |
} | |
if (sum == 1) | |
return true; | |
n = sum; | |
} | |
return false; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment