简体   繁体   中英

count the digits of a number with recursion

#include<iostream>
using namespace std;

bool recursion(int numb, int k, int br)
{
    if(br==1) return (numb==k);
    return k==(numb%10) || recursion(numb/10,k,br-1);

}

int main(){
    int num,n;
    cin>>num;
    n=num;
    int p;
    cin>>p;
    int br=1;
    while(n>10){
        n=n/10;
        br++;
    }
    cout<<br<<endl;
    cout<<recursion(num,p,br);
    return 0;
}

This is the whole program for counting the digits of a number , but it doesn't work for numbers with more than 10 digits. Does anybody know why?

First, your recursive program is not counting the digits in a number, it checks if a particular digit k is present within the last br digits of the number numb .

It does not work for numbers with more than ten digits because the largest number on your system that int can represent has ten digits. On 32-bit systems it is 2,147,483,647 .

To make it work with more digits, use a larger data type - say, long long , or uint64_t .

On a 32-bits machine, integers are 32 bits long. The largest signed integer you can get is 2^31 - 1 = 2147483647 which has 10 digits. You've got to use strings to allow for arbitrarily large numbers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM