---
# System prepended metadata

title: 974. Subarray Sums Divisible by K
tags: [Leetcode]

---

<style>
    html, body, .ui-content {
    background: #222222;
    color: #00BFFF;
}
    /* 設定 code 模板 */
    .markdown-body code,
.markdown-body tt {
    background-color: #ffffff36;
}
.markdown-body .highlight pre,
.markdown-body pre {
    color: #ddd;
    background-color: #00000036;
}
.hljs-tag {
    color: #ddd;
}
.token.operator {
  background-color: transparent;
}    
/* 設定連結 */
a,
.open-files-container li.selected a {
    color: #89FFF8;
    
}
a:hover,
.open-files-container li.selected a:hover {
    color: #89FFF890;
}
   
</style>

###### tags: `Leetcode`

# 974. Subarray Sums Divisible by K

###### Link : https://leetcode.com/problems/subarray-sums-divisible-by-k/description/

## 題目
找到加總整除k的子陣列數量
## 程式碼

```cpp=
class Solution {
public:
    int subarraysDivByK(vector<int>& nums, int k) {
        const int n = nums.size();
        int ans = 0;
        vector<int> Count(k, 0);//計算這個餘數出現幾次
        Count[0] = 1;
        for(int i = 0, sum = 0;i < n;i++){//sum為prefix % k
            sum = (sum + nums[i] % k + k) % k;
            //加上nums[i]%k並更新sum //+k讓餘數變成非負整數
            ans += Count[sum];//加上左邊餘數有相同數字的數量 也就是子陣列的起點
            Count[sum]++;//增加這次餘數出現的數量
        }
        return ans;
    }
};
```
## Date 
### 2023/1/19