Skip to content

Commit d2cc03a

Browse files
authored
Update count-substrings-divisible-by-last-digit.cpp
1 parent 13bfa3d commit d2cc03a

File tree

1 file changed

+49
-1
lines changed

1 file changed

+49
-1
lines changed

C++/count-substrings-divisible-by-last-digit.cpp

+49-1
Original file line numberDiff line numberDiff line change
@@ -69,10 +69,58 @@ class Solution {
6969
}
7070
};
7171

72+
// Time: O(d * n)
73+
// Space: O(d)
74+
// case works, math, freq table
75+
class Solution2 {
76+
public:
77+
long long countSubstrings(string s) {
78+
int64_t result = 0;
79+
vector<int> cnt;
80+
81+
// digit 4
82+
for (int i = 0; i < size(s); ++i) {
83+
if (s[i] == '4') {
84+
++result;
85+
if (i - 1 >= 0 && stoi(s.substr(i - 1, 2)) % 4 == 0) {
86+
result += i;
87+
}
88+
}
89+
}
90+
// digit 8
91+
for (int i = 0; i < size(s); ++i) {
92+
if (s[i] == '8') {
93+
++result;
94+
if (i - 1 >= 0 && stoi(s.substr(i - 1, 2)) % 8 == 0) {
95+
++result;
96+
}
97+
if (i - 2 >= 0 && stoi(s.substr(i - 2, 3)) % 8 == 0) {
98+
result += i - 1;
99+
}
100+
}
101+
}
102+
for (int d = 1; d <= 9; ++d) {
103+
if (d == 4 || d == 8) {
104+
continue;
105+
}
106+
cnt.assign(d, 0);
107+
for (int i = 0, remain = 0, base = 1; i < size(s); ++i, base = (base * 10) % d) {
108+
remain = (remain + base * (s[(size(s) - 1) - i] - '0')) % d;
109+
result += cnt[remain];
110+
if (s[(size(s) - 1) - i] - '0' == d) {
111+
++result;
112+
++cnt[remain];
113+
}
114+
}
115+
}
116+
return result;
117+
}
118+
};
119+
72120
// Time: O(d^2 * n)
73121
// Space: O(d^2)
74122
// dp
75-
class Solution2 {
123+
class Solution3 {
76124
public:
77125
long long countSubstrings(string s) {
78126
int64_t result = 0;

0 commit comments

Comments
 (0)