Recursive digit sum

Categories:

Problem

Given an integer number $n$ calculate sum of its digits recursively: repeatedly add all its digits until the result has only one digit.

Complexity

  • Time: $O(1)$
  • Space: $O(1)$

Recursive Digit Sum (HackerRank)

Recursive Digit Sum | HackerRank

Solution

 1#include <bits/stdc++.h>
 2
 3using namespace std;
 4
 5int main() {
 6    string n;
 7    int k;
 8    long p{};
 9
10    cin >> n >> k;
11
12    for (const auto& c : n)
13        p += c - '0';
14    p *= k;
15
16    cout << (1 + (p - 1) % 9) << endl;
17
18    return 0;
19}

Add Digits (LeetCode)

Add Digits - LeetCode

Solution

1class Solution {
2public:
3    int addDigits(int num) {
4        return 1 + (num - 1) % 9;
5    }
6};