A good way into this one is to ask: what do we need to remember so we never redo work blindly? For 202. Happy Number, the solution in this repository is mainly a straightforward implementation solution.
Guide
What?
The first job is to translate the English prompt into state, transition, and stopping conditions. Instead of trying to be clever immediately, read the code as a sequence of questions:
- What state are we keeping?
- How do we move from one state to the next?
- When do we know the answer is already determined?
For this file, the main tools are: straightforward implementation.
Guide
When?
This pattern shows up when the brute force version has too many repeated checks, too many possible branches, or too much bookkeeping to do by hand. The accepted code reduces that pressure by storing exactly the information that remains useful later.
The important function names to track are isHappy.
Guide
Why?
The win comes from making each line carry responsibility: store the useful state, discard the rest, keep moving.
- A set is doing the membership or uniqueness work, which keeps the main loop readable.
- The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.
Guide
How?
Walk through the solution in this order:
- Read the setup variables first.
- Follow the main loop or recursive helper next.
- Watch where invalid states get skipped.
- Check which value survives to the return statement.
The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.
Guide
Complexity
- Time: O(n) to O(n log n), depending on the dominant loop or data structure operation
- Space: O(n) in the usual case for auxiliary containers or recursion
Guide
C++ Solution
Your submission
The accepted solution
01/**
02Write an algorithm to determine if a number is "happy".
03
04A 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.
05
06Example:
07
08Input: 19
09Output: true
10Explanation:
1112 + 92 = 82
1282 + 22 = 68
1362 + 82 = 100
1412 + 02 + 02 = 1
15**/
16
17//Runtime: 4 ms, faster than 100.00% of C++ online submissions for Happy Number.
18//Memory Usage: 8.4 MB, less than 57.57% of C++ online submissions for Happy Number.
19class Solution {
20public:
21 bool isHappy(int n) {
22 int tmp = 0;
23 set<int> visited;
24
25 while(true){
26 tmp = 0;
27 while(n > 0){
28 tmp += pow((n%10), 2);
29 n/=10;
30 }
31 n = tmp;
32 if(n == 1){
33 break;
34 }else if(visited.find(n)!=visited.end()){
35 return false;
36 }
37 visited.insert(n);
38 }
39 return true;
40 }
41};
Cost