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
  • 相关阅读:
    第五周课后作业
    第五周读书笔记
    PB16120853+JL17110067
    第一次个人作业报告
    《编程匠艺》读书笔记----第四周
    软工第一次个人作业博客(一)
    软工第一次个人作业博客(二)
    《程序员修炼之道》读书笔记(二)--第三周
    关于在aspx前台使用后台变量的问题
    sql语句优化SQL Server
  • 原文地址:https://www.cnblogs.com/cpoint/p/3400282.html
Copyright © 2011-2022 走看看