Skip to content

Instantly share code, notes, and snippets.

@ozkansari
Created April 12, 2020 16:34
Show Gist options
  • Save ozkansari/5a9d9ab43564b65c2aee02d4c8f37317 to your computer and use it in GitHub Desktop.
Save ozkansari/5a9d9ab43564b65c2aee02d4c8f37317 to your computer and use it in GitHub Desktop.
Write an algorithm to determine if a number n is "happy". 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 equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Th…
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class HappyNumber {
public static void main(String[] args) {
HappyNumber problem = new HappyNumber();
boolean result1 = problem.isHappy(19);
System.out.println("Expected: true, Result: " + result1);
}
/**
* Determine if a number n is "happy". <br/>
*
* 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 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.
*
* @param n
* @return True if n is a happy number, and False if not.
*/
public boolean isHappy(int n) {
Set<Integer> allResultSet = new HashSet<>();
int result = n;
while(result != 1) {
result = digitsSumOfSquares(result);
if(allResultSet.contains(result)){
return false;
}
allResultSet.add(result);
}
return true;
}
private int digitsSumOfSquares(int number) {
int sum = 0;
List<Integer> digitList = findDigits(number);
for(Integer digit : digitList) {
sum += Math.pow( digit, 2 );
}
return sum;
}
private List<Integer> findDigits(int number){
List<Integer> digits = new ArrayList<>();
while (number > 0) {
digits.add(0, Integer.valueOf( number % 10 ) ) ;
number = number / 10;
}
return digits;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment