zoukankan      html  css  js  c++  java
  • (Problem 36)Doublebase 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 }
    C代码

     下面是根据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 }
    C代码

    谢谢garbageMan兄的指正,大家还有什么优化方法可以留言,一起交流

    Answer:
    872187
  • 相关阅读:
    Java正则表达式教程
    神奇3D圣诞树祝广大技术人员圣诞快乐!
    SQL语句:Group By总结
    最全面的笔记本基本硬件参数介绍
    已安装的Flash Player不支持FlexBuilder调试
    模拟火车带你游西藏
    javascript技巧参考
    flex 与asp.net 配合之道
    ‍Android 尺寸和分辨率
    【windows】windows生产力/性能分析工具下载链接归档
  • 原文地址:https://www.cnblogs.com/cpoint/p/3400282.html
Copyright © 2011-2022 走看看