---
# System prepended metadata

title: 0974. Subarray Sums Divisible by K
tags: [Leetcode, HashMap, Prefix Sum, Medium]

---

# 0974. Subarray Sums Divisible by K
###### tags: `Leetcode` `Medium` `Prefix Sum` `HashMap`
Link: https://leetcode.com/problems/subarray-sums-divisible-by-k/
## 思路
和其他用prefixSum+HashMap的题目差不多(e.g. [1524. Number of Sub-arrays With Odd Sum](https://leetcode.com/problems/number-of-sub-arrays-with-odd-sum/))
唯一要注意的地方是因为有可能sum是负数 在java里面余数也会是负数 所以用((sum%k+k)%k)
## Code
```java=
class Solution {
    public int subarraysDivByK(int[] nums, int k) {
        int sum = 0, ans = 0;
        Map<Integer, Integer> map = new HashMap<>();
        map.put(0,1);
        for(int i=0; i<nums.length; i++){
            sum += nums[i];
            ans += map.getOrDefault((sum%k+k)%k, 0);
            map.put((sum%k+k)%k, map.getOrDefault((sum%k+k)%k,0)+1);
        }
        return ans;
    }
}
```