> For the complete documentation index, see [llms.txt](https://maksimdan.gitbook.io/interview-practice-problems/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://maksimdan.gitbook.io/interview-practice-problems/leetcode_sessions/258_add_digits.md).

# 258 Add Digits

Given a non-negative integer num, repeatedly add all its digits until the result has only one digit.

For example:

Given num = 38, the process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit, return it.

Follow up: Could you do it without any loop/recursion in O(1) runtime?

```cpp
  #include <iostream>
  #include <math.h>
  using namespace std;

  //https://www.wikiwand.com/en/Digit_sum
  int digitSum(int number)
  {
      int compare = floor(log10(number));
      long long int sum = 0;
      for (int count = 0; count <= compare; count++)
      {
          int power1 = (pow(10, count + 1));
          int power2 = (pow(10, count));
          sum += (1 / (pow(10, count)))*(number % power1 - number % power2);
      }
      return sum;
  }

  int main()
  {
      cout << digitSum(123456789);
  }
```
