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?

  #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);
  }

Last updated