Intuition¶
We only care about the non-zero digits of n. Concatenating them in order is the
same as rebuilding a number that skips every zero, and the digit sum of that number
equals the sum of those same non-zero digits. So one pass extracting digits from the
least-significant end lets us build x and accumulate sum simultaneously.
Approach: Digit Extraction¶
- Walk
nfrom the last digit to the first via repeatedn % 10/n /= 10. - Add every digit to
sumDigit(zeros contribute nothing anyway). - For each non-zero digit, place it into
xat the current power of ten and advance the multiplierpow10. Since we process digits from least significant to most significant and only skip zeros, the non-zero digits keep their original relative order inx. - Return
x * sumas a 64-bit value.
Complexity¶
- Time complexity: $$O(\log n)$$ — one step per digit of
n. - Space complexity: $$O(1)$$ extra space.
Code¶
Go¶
func sumAndMultiply(n int) int64 {
newN, pow10, sumDigitN := 0, 1, 0
for n > 0 {
digit := n % 10
sumDigitN += digit
if digit > 0 {
newN += digit * pow10
pow10 *= 10
}
n /= 10
}
return int64(newN * sumDigitN)
}