[LeetCode] Find Triangular Sum of an Array

2221. Find Triangular Sum of an Array

You are given a 0-indexed integer array nums, where nums[i] is a digit between 0 and 9 (inclusive).

The triangular sum of nums is the value of the only element present in nums after the following process terminates:

  1. Let nums comprise of n elements. If n == 1, end the process. Otherwise, create a new 0-indexed integer array newNums of length n - 1.
  2. For each index i, where 0 <= i < n - 1, assign the value of newNums[i] as (nums[i] + nums[i+1]) % 10, where % denotes modulo operator.
  3. Replace the array nums with newNums.
  4. Repeat the entire process starting from step 1.

Return the triangular sum of nums.

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
public:
int triangularSum(vector<int>& nums) {
int n = nums.size();
for(int ed = n - 1; ed >= 1; ed--) {
for(int i = 0; i < ed; i++) {
nums[i] = (nums[i] + nums[i + 1]) % 10;
}
}

return nums[0];
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/04/03/PS/LeetCode/find-triangular-sum-of-an-array/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.