sicily 2010. H Number

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.


试用一下C++的新函数类型bool与逻辑值true和false

枚举,提取各位数字,判断,计数,最后输出即可

View Code
 1 #include<iostream>
 2 using namespace std;
 3 
 4 int num[7];
 5 
 6 bool isHnumber( int n )
 7 {
 8     if ( n < 100 )
 9         return true;
10     
11     int i = 0;
12     do{
13         num[i++] = n % 10;
14         n /= 10;
15     }while( n != 0 );
16     
17     for ( int j = 1; j < i - 1; j++ )
18     {
19         if( num[j] != num[j - 1] + num[j + 1] )
20             if( num[j] != num[j - 1] - num[j + 1] )
21                 if( num[j] != num[j + 1] - num[j - 1] )
22                     return false;
23     }
24     
25     return true;
26 }
27 
28 int main()
29 {
30     int n, count = 0;
31     cin >> n;
32     for ( int i = 1; i <= n; i++ )
33         if( isHnumber(i) )
34             count++;
35             
36     cout << count << endl;
37     
38     return 0;
39 }

 

posted @ 2013-02-09 14:42  Joyee  阅读(296)  评论(0编辑  收藏  举报