Skip to content

Commit

Permalink
Fix indentation, compilation about trivial missing include, add tests.
Browse files Browse the repository at this point in the history
  • Loading branch information
iglesias committed Jun 12, 2024
1 parent 74586f8 commit 340a4ee
Showing 1 changed file with 45 additions and 31 deletions.
76 changes: 45 additions & 31 deletions leetcode/523.cpp
Original file line number Diff line number Diff line change
@@ -1,32 +1,46 @@
/*
Given an integer array and an integer k, return true if the arary has a
(continuous) subarray with length at least two whose elements of the subarray
is a multiple of k.
*/
#include <vector>

bool checkSubarraySum(vector<int>& nums, int k) {
const int n = static_cast<int>(nums.size());
if (n < 2) return false;
int i = 0, j = 1;
unsigned sum = 0;
while (i < n) {
sum += nums[i];
while (j < n) {
sum += nums[j];
if (!(sum % k)) return true;
j ++;
}
j--;
sum -= nums[i];
i++;
if (i == n) break;
while (j >= i + 1) {
if (!(sum % k)) return true;
sum -= nums[j];
j--;
}
sum -= nums[i];
i++, j +=2;
}
return false;
}
#include <gtest/gtest.h>

// Check if the arary has a (continuous) subarray of at least
// two elements whose sum is a multiple of k.
bool check_subarray_sum(const std::vector<int>& nums, int k)
{
const int n = static_cast<int>(nums.size());
if (n < 2) return false;
int i = 0, j = 1;
unsigned sum = 0;
while (i < n) {
sum += nums[i];
while (j < n) {
sum += nums[j];
if (!(sum % k)) return true;
j ++;
}
j--;
sum -= nums[i];
i++;
if (i == n) break;
while (j >= i + 1) {
if (!(sum % k)) return true;
sum -= nums[j];
j--;
}
sum -= nums[i];
i++, j +=2;
}
return false;
}

TEST(CheckSubarraySumDivisibility, a)
{
const std::vector nums{23, 2, 6, 4, 7};
EXPECT_EQ(check_subarray_sum(nums, 6), true);
EXPECT_EQ(check_subarray_sum(nums, 13), false);
}

int main(int argc, char **argv)
{
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}

0 comments on commit 340a4ee

Please sign in to comment.