Math 3099. Harshad Number ¶ Time: $O(\log x)$ Space: $O(1)$ C++JavaPython 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17class Solution { public: int sumOfTheDigitsOfHarshadNumber(int x) { const int digitSum = getDigitSum(x); return x % digitSum == 0 ? digitSum : -1; } private: int getDigitSum(int x) { int digitSum = 0; while (x > 0) { digitSum += x % 10; x /= 10; } return digitSum; } }; 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15class Solution { public int sumOfTheDigitsOfHarshadNumber(int x) { final int digitSum = getDigitSum(x); return x % digitSum == 0 ? digitSum : -1; } private int getDigitSum(int x) { int digitSum = 0; while (x > 0) { digitSum += x % 10; x /= 10; } return digitSum; } } 1 2 3 4 5 6 7class Solution: def sumOfTheDigitsOfHarshadNumber(self, x: int) -> int: digitSum = self._getDigitSum(x) return digitSum if x % digitSum == 0 else -1 def _getDigitSum(self, num: int) -> int: return sum(int(digit) for digit in str(num))