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
  • 相关阅读:
    Http中的patch
    如何实现腾讯地图的路径规划功能?
    各类数据库分页SQL语法
    ABC222F
    ABC222 G
    LG5308 [COCI2019] Quiz(wqs二分+斜率优化DP)
    [USACO21OPEN] Portals G(Kruskal)
    【做题笔记】SP27379 BLUNIQ
    【做题笔记】CF938C Constructing Tests
    CSP-J/S2021 自闭记
  • 原文地址:https://www.cnblogs.com/cpoint/p/3400282.html
Copyright © 2011-2022 走看看