Reputation: 53
#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?
Upvotes: 1
Views: 276
Reputation: 3191
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.
Upvotes: 0
Reputation: 726599
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
.
Upvotes: 1