C++ 中统计整数中孔洞的数量
给定一个包含数字 0 到 9 中孔洞数量的数组 holes[10]。目标是找到给定输入整数的孔洞数量。已知 - holes[] = { 2, 1, 1, 0, 0, 1, 1, 1, 0 }
例如
输入
number = 239143
输出
Count the number of holes in an integer are: 3
解释
We will count holes given in holes[] 239143 ( 1+0+0+2+0+0 )
输入
number = 12345
输出
Count the number of holes in an integer are: 3
解释
We will count holes given in holes[] 12345 ( 1+1+0+0+1)
以下程序中使用的方案如下 −
只需使用 num%10 获取每个最左边的数字,并将 holes[num%10] 中的孔洞计数添加到 count 中。然后将数字 num 减去 10。
输入一个整数。
初始化 holes[] 数组。
函数 holes_integer(int number, int holes[]) 返回整数中孔洞数量的计数。
将初始计数设置为 0。
遍历直到 number > 0。
将最左边的数字作为 temp = number % 10。将 holes[temp] 添加到 count 中。
将数字减少 10。
最后返回 count 作为结果。
示例
#include <bits/stdc++.h>
using namespace std;
int holes_integer(int number, int holes[]){
int count = 0;
while (number > 0){
int temp = number % 10;
count = count + holes[temp];
number = number/10;
}
return count;
}
int main(){
int number = 239143;
int holes[] = { 2, 1, 1, 0, 0, 1, 1, 1, 0};
cout<<"Count the number of holes in an integer are: "<<holes_integer(number, holes);
return 0;
}输出
如果我们运行上面的代码,它将生成以下输出:
Count the number of holes in an integer are: 2
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP