简体   繁体   English

用递归计数数字

[英]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. 这是整个用于计算数字位数的程序,但不适用于10位以上的数字。 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 . 首先,您的递归程序没有计算数字中的位数,而是检查数字numb的最后br数字中是否存在特定的数字k

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. 它不适用于十位数以上的数字,因为int可以代表系统上的最大数字为十位数。 On 32-bit systems it is 2,147,483,647 . 在32位系统上为2,147,483,647

To make it work with more digits, use a larger data type - say, long long , or uint64_t . 要使用更多数字,请使用更大的数据类型,例如long longuint64_t

On a 32-bits machine, integers are 32 bits long. 在32位计算机上,整数为32位长。 The largest signed integer you can get is 2^31 - 1 = 2147483647 which has 10 digits. 您可以获得的最大有符号整数是2^31 - 1 = 2147483647 ,它有10位数字。 You've got to use strings to allow for arbitrarily large numbers. 您必须使用字符串来允许任意大数字。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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