Time Limit: 1 secs, Memory Limit: 256 MB
Description
Hengheng is a math nerd. Today he invents a new kind of numbers so called H number. These numbers satisfy that each digit is either the sum or the difference of the adjacent digits. Notice that the first and the last digit are not constrained, except that the first digit is not zero (i.e. 0012 is invalid).
For example, d = 134734 is an H number, because
d1 = 1
d2 = 3 = 4 – 1 = d3 – d1
d3 = 4 = 7 – 3 = d4 – d2
d4 = 7 = 4 + 3 = d3 + d5
d5 = 3 = 7 – 4 = d4 – d6
d6 = 4
While q = 4561 is not an H number, because
q2 != q1 + q3 = 10 and q2 != q1 – q3 = -2 and q2 != q3 – q1 = 2
Here comes your problem. Given a number N, calculate the quantity of distinct H numbers less than or equal to N.
Input
There is only one integer N(<=1000000).
Output
Output the quantity of distinct H number less than or equal to N.
Sample Input
1111
Sample Output
227
Problem Source
每周一赛:2010中山大学新手赛
^_^ Just do it!
#include <iostream>
#include <string>
#include <cmath>
using namespace std;
bool valid (int N)
{
string str;
while (N != 0)
{
str += N % 10 + 48;
N /= 10;
}
for (int i = 1; i < str.size() - 1; i++)
if (str[i] - 48 != str[i - 1] + str[i + 1] - 96 && str[i] - 48 != abs(str[i - 1] - str[i + 1]))
return false;
return true;
}
int main()
{
int N, T = 0;
cin >> N;
do
{
if (valid(N)){
T++;
}
}
while (--N);
cout << T << endl;
return 0;
}