1 second
256 megabytes
standard input
standard output
Max wants to buy a new skateboard. He has calculated the amount of money that is needed to buy a new skateboard. He left a calculator on the floor and went to ask some money from his parents. Meanwhile his little brother Yusuf came and started to press the keys randomly. Unfortunately Max has forgotten the number which he had calculated. The only thing he knows is that the number is divisible by 4.
You are given a string s consisting of digits (the number on the display of the calculator after Yusuf randomly pressed the keys). Your task is to find the number of substrings which are divisible by 4. A substring can start with a zero.
A substring of a string is a nonempty sequence of consecutive characters.
For example if string s is 124 then we have four substrings that are divisible by 4: 12, 4, 24 and 124. For the string 04 the answer is three: 0, 4, 04.
As input/output can reach huge size it is recommended to use fast input/output methods: for example, prefer to usegets/scanf/printf instead of getline/cin/cout in C++, prefer to use BufferedReader/PrintWriter instead ofScanner/System.out in Java.
The only line contains string s (1 ≤ |s| ≤ 3·105). The string s contains only digits from 0 to 9.
Print integer a — the number of substrings of the string s that are divisible by 4.
Note that the answer can be huge, so you should use 64-bit integer type to store it. In C++ you can use the long long integer type and in Java you can use long integer type.
124
4
04
3
5810438174
9
题意:
给一个数字串,问有多少子串的代表的数字能被4整除。
题解:
首先,容易想到100是4的倍数。
所以我们只用考虑后两位数字就能够判断一个数字能否被4整除,因为
x*100+y=y (mod 4)
其中x代表超过100的数字部分。
于是只需要对所有相邻两位判断,如果某两位可以被4整除,那么以这两位结尾的所有子串都是可行的。
比如12344,44能被4整除,那么44,344,2344,12344都能被4整除。
在单独考虑只有一个位的子串就好。
#include <cstdio>
#include <string>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <cstdlib>
using namespace std; const int N = ;
char str[N]; int main() {
scanf("%s", str);
long long ans = ;
int n = strlen(str);
for(int i = ; i < n; ++i)
if((str[i] - '') % == ) ++ans;
for(int i = ; i < n; ++i) {
int x = (str[i - ] - '') * + str[i] - '';
if(x % == ) ans += i;
}
cout << ans << endl;
return ;
}