Difficulty: Easy | Acceptance: 55.90% | Paid: No Topics: Math
You are given a positive integer n.
Let sum be the sum of the non-zero digits of n.
Let concat be the integer formed by concatenating the non-zero digits of n in the same order they appear in n.
Return the product of sum and concat.
- Examples
- Constraints
- String Manipulation
- Mathematical Extraction
Examples
Example 1
Input:
n = 10203004
Output:
12340
Explanation: The non-zero digits are 1, 2, 3, and 4. Thus, x = 1234.
The sum of digits is sum = 1 + 2 + 3 + 4 = 10.
Therefore, the answer is x * sum = 1234 * 10 = 12340.
Example 2
Input:
n = 1000
Output:
1
Explanation: The non-zero digit is 1, so x = 1 and sum = 1.
Therefore, the answer is x * sum = 1 * 1 = 1.
Constraints
1 <= n <= 10^9
String Manipulation
Intuition Convert the integer to a string to easily iterate over each digit, filter out zeros, and reconstruct the concatenated number.
Steps
- Convert the integer
nto a string. - Iterate through each character in the string.
- If the character is not ‘0’, add its integer value to the sum and append it to a new string representing the concatenated number.
- Convert the concatenated string back to an integer.
- Return the product of the sum and the concatenated integer.
class Solution:
def sumOfDigitsAndConcat(self, n: int) -> int:
s = str(n)
concat_str = ""
total = 0
for ch in s:
if ch != '0':
total += int(ch)
concat_str += ch
return total * int(concat_str)
Complexity
- Time: O(d) where d is the number of digits in n.
- Space: O(d) to store the string representation.
- Notes: Simple to implement but uses extra space for strings.
Mathematical Extraction
Intuition Extract digits using modulo and division operations to avoid string conversion overhead. Since modulo extracts digits from right to left, we build the number in reverse and then reverse it back.
Steps
- Initialize
sum,rev_concat, andtemp(copy of n) to 0. - Loop while
tempis greater than 0. - Extract the last digit using
temp % 10. - If the digit is not 0, add it to
sumand append it torev_concat(rev_concat = rev_concat * 10 + digit). - Remove the last digit by dividing
tempby 10. - Reverse
rev_concatto get the correctconcatorder. - Return the product of
sumandconcat.
class Solution:
def sumOfDigitsAndConcat(self, n: int) -> int:
rev_concat = 0
total = 0
temp = n
while temp > 0:
digit = temp % 10
if digit != 0:
total += digit
rev_concat = rev_concat * 10 + digit
temp //= 10
# Reverse rev_concat to get correct order
concat = 0
while rev_concat > 0:
concat = concat * 10 + rev_concat % 10
rev_concat //= 10
return total * concat
Complexity
- Time: O(d) where d is the number of digits in n.
- Space: O(1) auxiliary space.
- Notes: More efficient space-wise as it avoids string allocations.