21xrx.com
2025-03-21 18:07:12 Friday
文章检索 我的文章 写文章
C++统计2的个数
2023-06-30 10:54:40 深夜i     8     0
C++ 统计 2 个数

在C++编程中,统计2的个数是一项基本任务。在这篇文章中,我们将介绍几种不同的方法来完成这项任务。

方法1:使用循环

使用循环可以很容易地统计2的个数。我们可以先将数字转换为字符串,然后遍历字符串中的每个字符,如果字符是'2',则将计数器加1。

例如,以下代码展示了如何统计一个整数中2的个数:

int countTwos(int n){
  int count = 0;
  string str = to_string(n);
  for(int i=0; i<str.length(); i++){
    if(str[i] == '2'){
      count++;
    }
  }
  return count;
}

注意,我们使用了to_string()函数来将整数转换为字符串。这个函数需要C++11及以上版本的支持。

方法2:使用递归

使用递归也是一种有效的方法来统计2的个数。我们可以将数字拆分成两个部分:最高位和其余部分。如果最高位是2,则将计数器加上其余部分中2的个数,并递归统计最高位后面的数中2的个数。

例如,以下代码展示了如何使用递归统计一个整数中2的个数:

int countTwosHelper(int n){
  if (n == 0) return 0;
  
  int power = 1;
  while (10*power <= n) power *= 10;
  
  int firstDigit = n / power;
  int remainder = n % power;
  
  int count = 0;
  if (firstDigit > 2) {
    count += power;
  } else if (firstDigit == 2) {
    count += remainder + 1;
  }
  
  count += firstDigit * countTwosHelper(power-1);
  count += countTwosHelper(remainder);
  
  return count;
}
int countTwos(int n){
  if (n < 2) return 0;
  return countTwosHelper(n);
}

方法3:使用数学方法

最后,我们介绍一种使用数学方法的统计2的个数的方法。我们可以使用排列组合的方法,计算每一位为2、每两位为2、每三位为2等等的数量,然后求和。

例如,以下代码展示了如何使用数学方法统计一个整数中2的个数:

int countTwos(int n){
  if (n < 2) return 0;
  
  int count = 0;
  int power = 1;
  int lastDigit = 0;
  while (n > 0) {
    int digit = n % 10;
    
    count += digit * lastDigit * power / 10;
    if (digit == 2) {
      count += n % power + 1 + lastDigit * power;
    } else if (digit > 2) {
      count += power;
    }
    
    lastDigit = lastDigit + digit * power;
    power *= 10;
    n /= 10;
  }
  
  return count;
}

总结

以上就是三种不同的方法来统计2的个数。使用循环和递归是两种常见的方法,但是数学方法更加高效。根据具体问题的特点,选择合适的方法可以节省时间和精力。

  
  

评论区