Skip to main content

3754. Concatenate Non-Zero Digits and Multiply by Sum I

Easy
Description

You are given an integer n.

Form a new integer x by concatenating all the non-zero digits of n in their original order. If there are no non-zero digits, x = 0.

Let sum be the sum of digits in x.

Return an integer representing the value of x * sum.

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:

  • 0 <= n <= 10910^9

解題思路

先按照題目描述暴力解,直接把題目描述轉成程式碼。

var sumAndMultiply = function (n) {
const arrN = Array.from(String(n), Number); // 把傳入的數字先轉成陣列
const noZeros = arrN.filter((num) => num !== 0); // 把陣列中的 0 去掉
const noZerosString = noZeros.join(""); // 把去掉 0 後的陣列轉成字串

let sumOfNoZeros = noZeros.reduce((acc, curr) => acc + curr, 0); // 把去掉 0 後的陣列加總

return noZerosString * sumOfNoZeros; // 最後把去掉 0 後的字串與加總的數字相乘便是答案
};

心得

Submit 後發現效率滿差的,之後要嘗試用非暴力解