Live Batches
Masterclasses
Menu
Free Courses
Account
Login / Sign Up

Check Whether a Number Is a Happy Number

Basic Acceptance 85.46% Points 10.00

You are given a positive integer n. Repeatedly replace the number with the sum of the squares of its digits. Your task is to determine whether this process eventually reaches 1.

If the process reaches 1, the number is called a happy number, and you should return Yes. If the process enters a cycle that never reaches 1, return No.

Examples
Example 1

Input: n = 19
Output: Yes
Explanation: The process follows 19 → 82 → 68 → 100 → 1, so the number is happy.

Example 2

Input: n = 4
Output: No
Explanation: The process enters a repeating cycle that never reaches 1, so 4 is not a happy number.

Example 3

Input: n = 1
Output: Yes
Explanation: The number is already 1, so it is a happy number.

Constraints
  • 1 = n = 10?
Companies
Flipkart Infosys BNY Mellon
Topics
Data Structures Basics
Solution.cs C#JavaPythonC++Javascript

Unlock the code editor

Sign in to write, run, and submit your solution against the full test suite.

  • Run code against sample & hidden test cases
  • Save submissions and track your streak
  • Compare with editorial & community solutions