数字出现次数(Number-ception)C

时间:2014-12-26 13:14:03

标签: c string recursion

我需要帮助解决C中的问题。所以我基本上试图找出如何在一个数字中看到一个数字的次数,例如:

16 in 5167163 = 2
33 in 34333 = 1

但问题是这个数字不应该重叠,比如333中的33只是一次。我需要知道如何做到这一点。

到目前为止

代码:

#include <stdio.h>
#include <math.h>

int main()
{
    int n,i,j;
    scanf("%d",&n);
    int a[n][2];

    for(i=0;i<n;i++)
    {
        for(j=0;j<2;j++)
        {
            scanf("%d",&a[i][j]);
        }
    }


    return 0;
}

2 个答案:

答案 0 :(得分:2)

尝试以下

#include <stdio.h>
#include <stdlib.h>

size_t count(  int x, int y )
{
    const unsigned int BASE = 10;
    unsigned int a = abs( x );
    size_t n = 0;


    do
    {
        unsigned int z = a;
        unsigned int b = abs( y );
        _Bool equal = 0;

        do
        {
            equal = a % BASE == b % BASE;
            a /= BASE;
            b /= BASE;
        } while ( equal && a != 0 && b != 0 );

        if ( b == 0 && equal )
        {
            ++n;    
        }
        else
        {
            a = z / BASE;
        }
    } while ( a );

    return n;
}

int main(void) 
{
    printf( "count( 5167163, 16 ) = %zu\n", count( 5167163, 16 ) );
    printf( "count( 34333, 33 ) = %zu\n", count( 34333, 33) );
    printf( "count( 1000, 0 ) = %zu\n", count( 1000, 0) );
    printf( "count( 12323, 123 ) = %zu\n", count( 12323, 123 ) );
    printf( "count( 33333, 33 ) = %zu\n", count( 33333, 33 ) );

    return 0;
}

输出

count( 5167163, 16 ) = 2
count( 34333, 33 ) = 1
count( 1000, 0 ) = 3
count( 12323, 123 ) = 1
count( 33333, 33 ) = 2

如果您的编译器不支持_Bool类型,则可以改为使用int类型。

int equal = 0;

答案 1 :(得分:1)

这是纯数字解决方案。它不是用C语言编写的,而是它的演练如何做到这一点。我认为在这里发生的事情非常明显。 我在ruby控制台中快速完成了。你可以清楚地看到那里的算法。 祝你好运

2.1.4 :001 > a = 5167163
 => 5167163
2.1.4 :002 > b = 16
 => 16
2.1.4 :003 > c = 10
 => 10
2.1.4 :004 > found = 0
 => 0
2.1.4 :005 > (a - b) % c
 => 7
2.1.4 :006 > a = a / (c**1)
 => 516716
2.1.4 :007 > (a - b) % c
 => 0
2.1.4 :008 > found += 1
 => 1
2.1.4 :009 > a = a / (c**2) # we have to power the radix to number of digits in b (use log(b, 10) for that
 => 5167
2.1.4 :010 > (a - b) % c
 => 1
2.1.4 :011 > a = a / (c**1)
 => 516
2.1.4 :012 > (a - b) % c
 => 0
2.1.4 :013 > found += 1
 => 2
2.1.4 :014 > a = a / (c**2) # we have to power the radix to number of digits in b (use log(b, 10) for that
 => 5
2.1.4 :015 > (a - b) % c
 => 9
2.1.4 :016 > a = a / (c**1)
 => 0
2.1.4 :017 >

如果要获得给定基数中数字的位数,可以使用给定基数的数学日志(将结果放在地板上)。

享受