하루의 쉼터

[LeetCode] 288. Add Digits 본문

Coding Test/LeetCode

[LeetCode] 288. Add Digits

Changun An 2020. 11. 16. 23:51
반응형

Question
Given a non-negative integer num, repeatedly add all its digits until the result has only one digit.
Input: 38
Output: 2
Explanation: The process is like: 3 + 8 = 11, 1 + 1 = 2.
             Since 2 has only one digit, return it.

Solution.h //Hearder

#include<iostream>
#include<windows.h>
class Solution
{
private : 
    int input_num;

public:
    int addDigits(int num);
    int inputData();
    void outputData(int num);
};

 

Solution.cpp

#include "Solution.h"

int Solution::addDigits(int num)
{
	while (true) {
		if(num < 10)
			return num;
		num=(num/10)+(num%10);
	}
	return num;
}

int Solution::inputData()
{
	std::cout << "input : ";
	std::cin >> input_num;
	if (input_num < 0) {
		std::cout << "error"<<std::endl;
		std::system("cls");
		inputData();
	}
	return input_num;
}

void Solution::outputData(int num)
{
	std::cout << "output : " << num<<std::endl;
	std::system("pause");
}

 

Result
Runtime: 0 ms, faster than 100.00% of C++ online submissions for Add Digits.
Memory Usage: 6.3 MB, less than 27.32% of C++ online submissions for Add Digits.

 

github.com/Anchangun

 

Anchangun - Overview

어제보다 나은 오늘. Anchangun has 3 repositories available. Follow their code on GitHub.

github.com

 

반응형

'Coding Test > LeetCode' 카테고리의 다른 글

[LeetCode] 53. Maximum Subarray  (0) 2020.11.30
[LeetCode] 21. Merge Two Sorted Lists  (0) 2020.11.24
[LeetCode] 136. Single Number  (0) 2020.11.23
[LeetCode] 20. Valid Parentheses  (0) 2020.11.17
[LeetCode] 1. Two Sum  (0) 2020.11.17
Comments