| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 1 | 2 | 3 | 4 | 5 | 6 | |
| 7 | 8 | 9 | 10 | 11 | 12 | 13 |
| 14 | 15 | 16 | 17 | 18 | 19 | 20 |
| 21 | 22 | 23 | 24 | 25 | 26 | 27 |
| 28 | 29 | 30 | 31 |
- BinaryTree
- array
- treenode
- queue
- route
- Context
- priority_queue
- css
- component
- leetcode
- routes
- state
- React
- UE5
- bit
- JSX
- MySQL
- event
- Callback
- node.js
- nodeJS
- count
- Navigation
- c++
- server
- map
- Props
- DP
- 비트연산
- axios
- Today
- Total
우사미 코딩
[LeetCode] 202. Happy Number - 주옥같은 해피넘버 본문
1. 문제 링크
Happy Number - LeetCode
Can you solve this real interview question? Happy Number - 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 squar
leetcode.com
2. n을 한자리수로 쪼개서 제곱한 값을 모두 더한 값이 1이되면 해피넘버
input이 해피넘버이면 true 리턴, 아니면 false리턴
- Input: n = 19
1^2 + 9^2 = 82
8^2 + 2^2 = 68
6^2 + 8^2 = 100
1^2 + 0^2 + 0^2 = 1
3. 저딴식으로 더하면 circle이 될 수 있다

input넘버가 4인 경우에도 ㅈ같은 서클이 생성된다
ㅈ같은 서클은 모다? 해피넘버가 아니라는거시다; false를 리턴해야함
4. 한자릿수로 쪼개서 제곱근을 더한값들을 map에 저장해두쟈
만약 맵에 똑같은 결과값이 있다? 그럼 이것은 해피넘버가 아니기 때무넹 return false해야한다
input값의 최종 결과는 1이거나 circle이다
5. solution
class Solution {
public:
bool isHappy(int n) {
map<int, int> m;
while(n != 1){
int num = 0;
while(n > 0){
int curr = n % 10;
num += curr * curr;
n = n / 10;
}
if(num == 1)
break;
if(m[num]++ > 1)
return false;
n = num;
}
return true;
}
};'Leetcode' 카테고리의 다른 글
| [Leetcode] 15. 3Sum - two pointers를 사용하자 (0) | 2023.05.18 |
|---|---|
| [Leetcode] 153. Find Minimum in Rotated Sorted Array - 주옥같은 binary search (0) | 2023.05.17 |
| [Bit Manipulation] 190. Reverse Bits (0) | 2023.04.19 |
| [Bit Manipulation] 231. Power of Two (0) | 2023.04.18 |
| [Bit Manipulation] 191. Number of 1 Bits - n & (n-1) trick (0) | 2023.04.18 |