Description:
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.
- 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.
Return true
if n
is a happy number, and false
if not.
Examples:
Example 1:
Input: n = 19
Output: true
Explanation:
12 + 92 = 82
82 + 22 = 68
62 + 82 = 100
12 + 02 + 02 = 1
Example 2:
Input: n = 2
Output: false
Solution in Python:
Python
class Solution:
def isHappy(self, n: int) -> bool:
def get_next(number):
"""Helper function to get the next number in the sequence"""
total_sum = 0
while number > 0:
digit = number % 10 # Get the last digit
total_sum += digit * digit # Add the square of the digit to the total sum
number = number // 10 # Remove the last digit
return total_sum
seen_numbers = set() # Initialize a set to track seen numbers
while n != 1 and n not in seen_numbers:
seen_numbers.add(n) # Add the current number to the set
n = get_next(n) # Replace n with the sum of the squares of its digits
return n == 1 # If n is 1, return True, otherwise return False
# Example usage
sol = Solution()
print(sol.isHappy(19)) # Output: True
print(sol.isHappy(2)) # Output: False
Explanation:
- Helper function
get_next(number)
:- This function calculates the next number in the sequence by summing the squares of the digits of the current number.
- For example, for
number = 19
, it will calculate 12+92=1+81=82.
- Main logic in
isHappy
:- We use a
while
loop that continues as long asn
is not 1 andn
has not been seen before (to detect cycles). - Inside the loop, we add the current
n
to theseen_numbers
set. - We update
n
to the next number in the sequence using theget_next
function. - If
n
becomes 1, we exit the loop and returnTrue
. - If we detect a cycle (i.e.,
n
is found inseen_numbers
), we returnFalse
.
- We use a
Example Execution:
For n = 19
:
19→82→68→100→1 (Happy number, returns True
).
For n = 2
:
2→4→16→37→58→89→145→42→20→4 (Cycle detected, returns False
).
Solution in Javascript:
JavaScript
/**
* @param {number} n
* @return {boolean}
*/
var isHappy = function(n) {
// Helper function to get the next number in the sequence
const getNext = (number) => {
let totalSum = 0;
while (number > 0) {
let digit = number % 10; // Get the last digit
totalSum += digit * digit; // Add the square of the digit to the total sum
number = Math.floor(number / 10); // Remove the last digit
}
return totalSum;
};
let seenNumbers = new Set(); // Initialize a set to track seen numbers
// Loop until n becomes 1 (happy number) or we detect a cycle (number seen before)
while (n !== 1 && !seenNumbers.has(n)) {
seenNumbers.add(n); // Add the current number to the set
n = getNext(n); // Replace n with the sum of the squares of its digits
}
return n === 1; // If n is 1, return true, otherwise return false
};
// Example usage
console.log(isHappy(19)); // Output: true
console.log(isHappy(2)); // Output: false
Solution in Java:
Java
import java.util.HashSet;
import java.util.Set;
class Solution {
public boolean isHappy(int n) {
Set<Integer> seenNumbers = new HashSet<>(); // Initialize a set to track seen numbers
// Loop until n becomes 1 (happy number) or we detect a cycle (number seen before)
while (n != 1 && !seenNumbers.contains(n)) {
seenNumbers.add(n); // Add the current number to the set
n = getNext(n); // Replace n with the sum of the squares of its digits
}
return n == 1; // If n is 1, return true, otherwise return false
}
// Helper method to get the next number in the sequence
private int getNext(int number) {
int totalSum = 0;
while (number > 0) {
int digit = number % 10; // Get the last digit
totalSum += digit * digit; // Add the square of the digit to the total sum
number = number / 10; // Remove the last digit
}
return totalSum;
}
public static void main(String[] args) {
Solution sol = new Solution();
System.out.println(sol.isHappy(19)); // Output: true
System.out.println(sol.isHappy(2)); // Output: false
}
}
Solution in C#:
C#
using System;
using System.Collections.Generic;
public class Solution {
public bool IsHappy(int n) {
// Helper method to get the next number in the sequence
int GetNext(int number) {
int totalSum = 0;
while (number > 0) {
int digit = number % 10; // Get the last digit
totalSum += digit * digit; // Add the square of the digit to the total sum
number = number / 10; // Remove the last digit
}
return totalSum;
}
HashSet<int> seenNumbers = new HashSet<int>(); // Initialize a set to track seen numbers
// Loop until n becomes 1 (happy number) or we detect a cycle (number seen before)
while (n != 1 && !seenNumbers.Contains(n)) {
seenNumbers.Add(n); // Add the current number to the set
n = GetNext(n); // Replace n with the sum of the squares of its digits
}
return n == 1; // If n is 1, return true, otherwise return false
}
}