일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- git
- 앙상블
- machine learning
- loop
- C#
- BOJ
- dotenv
- type
- security
- generic
- leetcode
- Clone
- JavaScript
- vue.js
- VUE
- webpack
- AI
- npm
- scss
- TypeScript
- var
- bash
- docker
- Python
- condition
- nginx
- C++
- vuetify
- 보안
- property
Archives
- Today
- Total
ice rabbit programming
[LeetCode] 258. Add Digits 본문
728x90
https://leetcode.com/problems/add-digits/description/
Add Digits - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
처음에는 제목만 보고 이진수의 덧셈인 줄 알았는데, 그건 아니었다.
자연수가 주어지면, 각 자릿수의 합 결과가 한 자릿수가 될 때까지 계산하여 반환하는 문제이다.
(ex. 76 -> 7+6 -> 13 -> 1+3 -> 4)
특별한 로직은 없었고, 거의 브루트 포스 하게 풀었다. 처음에 한 자릿수가 들어오는 경우만 거르면 된다. 답변에서는 조건문으로 처음에 걸렀지만, while을 처음에 걸거나 하는 식으로 해도 될 듯하다.
class Solution {
public:
int addDigits(int num) {
if(num < 10) {
return num;
}
int result = 0;
int tempNum = num;
while(tempNum / 10 > 0) {
int tempNum2 = tempNum;
result = 0;
while(tempNum2 > 0) {
result += tempNum2 % 10;
tempNum2 /= 10;
}
tempNum = result;
}
return result;
}
};
728x90
'PS > LeetCode' 카테고리의 다른 글
[LeetCode] 58. Length of Last Word (0) | 2024.03.07 |
---|---|
[LeedCode] 268. Missing Number (0) | 2023.12.27 |
[LeetCode] 225. Implement Stack using Queues (0) | 2022.11.10 |
[LeetCode] 232. Implement Queue Using Stacks (0) | 2022.11.10 |
[LeetCode] 766. toeplitz-matrix (0) | 2022.11.10 |