(Problem 36)Double-base palindromes
The decimal number, 585 = 10010010012 (binary), is palindromic in both bases.
Find the sum of all numbers, less than one million, which are palindromic in base 10 and base 2.
(Please note that the palindromic number, in either base, may not include leading zeros.)
1 #include<stdio.h> 2 #include<math.h> 3 #include<stdbool.h> 4 5 bool test(int *a, int n) 6 { 7 bool flag = true; 8 for(int i = 0; i < n/2; i++) { 9 if(a[i] != a[n-i-1]) { 10 flag = false; 11 break; 12 } 13 } 14 return flag; 15 } 16 17 bool palindromes(int n, int base) //判断整数n在基为base时是否为回文数 18 { 19 int a[100]; 20 int i = 0; 21 while(n) { 22 a[i++] = n % base; 23 n /= base; 24 } 25 return test(a,i); 26 } 27 28 int main(void) 29 { 30 int sum = 0; 31 for(int i = 1; i <= 1000000; i++) 32 { 33 if(palindromes(i, 10) && palindromes(i, 2)) 34 sum += i; 35 } 36 printf("%d\n", sum); 37 return 0; 38 }
下面是根据garbageMan兄所提出的优化方法(具体解释详见本文留言)修改后的代码:
1 #include<stdio.h> 2 #include<stdbool.h> 3 4 bool test(int *a, int n) 5 { 6 bool flag = true; 7 for(int i = 0; i < n/2; i++) { 8 if(a[i] != a[n-i-1]) { 9 flag = false; 10 break; 11 } 12 } 13 return flag; 14 } 15 16 bool palindromes(int n, int base) //判断整数n在基为base时是否为回文数 17 { 18 int a[100]; 19 int i = 0; 20 while(n) { 21 a[i++] = n % base; 22 n /= base; 23 } 24 return test(a,i); 25 } 26 27 int main(void) 28 { 29 int sum = 0; 30 for(int i = 1; i <= 1000000; i += 2) 31 { 32 if(palindromes(i, 10) && palindromes(i, 2)) 33 sum += i; 34 } 35 printf("%d\n", sum); 36 return 0; 37 }
谢谢garbageMan兄的指正,大家还有什么优化方法可以留言,一起交流
Answer:
|
872187 |
作者:cpoint
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利.