Input: s ="12936"Output: 11Explanation:
Substrings `"29"`,`"129"`,`"293"` and `"2936"` are not divisible by their
last digit. There are 15 substrings in total, so the answer is`15 - 4 = 11`.
Input: s ="5701283"Output: 18Explanation:
Substrings `"01"`,`"12"`,`"701"`,`"012"`,`"128"`,`"5701"`,`"7012"`,`"0128"`,`"57012"`,`"70128"`,`"570128"`, and `"701283"` are all divisible
by their last digit. Additionally, all substrings that are just 1 non-zero
digit are divisible by themselves. Since there are 6 such digits, the answer
is`12 + 6 = 18`.
For each substring ending at position i, we want to check if the number formed by the substring is divisible by its last digit (if non-zero). Instead of checking all substrings, we can process from right to left, keeping track of remainders for each possible last digit.
classSolution {
public:longlong countDivisibleSubstrings(string s) {
longlong ans =0;
int n = s.size();
for (int d =1; d <=9; ++d) {
vector<int> cnt(d, 0);
int rem =0, p =1;
for (int i = n-1; i >=0; --i) {
rem = (rem + (s[i]-'0') * p) % d;
if (s[i]-'0'== d) ans++;
ans += cnt[rem];
cnt[rem]++;
p = (p *10) % d;
}
}
return ans;
}
};
classSolution {
publiclongcountDivisibleSubstrings(String s) {
long ans = 0;
int n = s.length();
for (int d = 1; d <= 9; ++d) {
int[] cnt =newint[d];
int rem = 0, p = 1;
for (int i = n-1; i >= 0; --i) {
rem = (rem + (s.charAt(i)-'0') * p) % d;
if (s.charAt(i)-'0'== d) ans++;
ans += cnt[rem];
cnt[rem]++;
p = (p * 10) % d;
}
}
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
classSolution {
funcountDivisibleSubstrings(s: String): Long {
var ans = 0Lval n = s.length
for (d in1..9) {
val cnt = IntArray(d)
var rem = 0var p = 1for (i in n-1 downTo 0) {
rem = (rem + (s[i]-'0') * p) % d
if ((s[i]-'0') == d) ans++ ans += cnt[rem]
cnt[rem]++ p = (p * 10) % d
}
}
return ans
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
classSolution:
defcountDivisibleSubstrings(self, s: str) -> int:
ans =0 n = len(s)
for d in range(1, 10):
cnt = [0] * d
rem =0 p =1for i in range(n-1, -1, -1):
rem = (rem + int(s[i]) * p) % d
if int(s[i]) == d:
ans +=1 ans += cnt[rem]
cnt[rem] +=1 p = (p *10) % d
return ans
impl Solution {
pubfncount_divisible_substrings(s: String) -> i64 {
let n = s.len();
let s = s.as_bytes();
letmut ans =0i64;
for d in1..=9 {
letmut cnt =vec![0; d];
letmut rem =0;
letmut p =1;
for i in (0..n).rev() {
rem = (rem + (s[i] -b'0') asusize* p) % d;
if (s[i] -b'0') asusize== d {
ans +=1;
}
ans += cnt[rem] asi64;
cnt[rem] +=1;
p = (p *10) % d;
}
}
ans
}
}