3754. Concatenate Non-Zero Digits and Multiply by Sum I
- Math
- String
- Simulation
TIME
O(d)
SPACE
O(1)
Intuition
Directly follow the definition: filter out zero digits, rebuild the number, sum its digits, multiply.
Approach
- Iterate over the digits of
n(left to right). - Keep the non-zero digits: append each to
x(asx = x * 10 + d) and adddtosum. - Return
x * sum. If there were no non-zero digits,xandsumstay 0, giving 0.
Complexity
- Time: O(d) where d = number of digits (at most 10)
- Space: O(1) (or O(d) if using a string)
Edge Cases
n = 0→ no non-zero digits → answer 0- All-zero-except-one (e.g.
1000) →x = 1,sum = 1 - Order matters:
xpreserves the original digit order - Max value
x * sumfits comfortably in 64-bit (x <= 10^9,sum <= 81)
Code
class Solution:
def concatenateAndMultiply(self, n: int) -> int:
"""
3754. Concatenate Non-Zero Digits and Multiply by Sum I
Time: O(d)
Space: O(1)
"""
x = 0
total = 0
for ch in str(n):
d = int(ch)
if d != 0:
x = x * 10 + d
total += d
return x * total/**
* 3754. Concatenate Non-Zero Digits and Multiply by Sum I
* Time: O(d)
* Space: O(1)
*/
class Solution {
public long concatenateAndMultiply(int n) {
long x = 0;
long total = 0;
for (char ch : Integer.toString(n).toCharArray()) {
int d = ch - '0';
if (d != 0) {
x = x * 10 + d;
total += d;
}
}
return x * total;
}
}