C++中范围内的单一数字计数
给定两个数字start和end代表一个范围。目标是找到[start, end]之间存在的单一数字的个数。
我们可以通过以下步骤检查数字是否为单一数字:如果我们取一个数字13,那么1² + 3² = 10,然后1² + 0² = 1,所以最终的和是1,所以13是单一数字。
例如
输入
start=1 end=20
输出
Count of Unary Numbers in a Range are: 5
解释
The numbers are : 1, 7, 10, 12, and 13
输入
start=50 end=100
输出
Count of Unary Numbers in a Range are: 7
解释
The numbers are − 59, 63, 67, 74, 75, 78, and 89
下面程序中使用的算法如下:
在1到9之间,数字1和7是单一数字。对于其他数字,我们将使用数字平方和,直到结果为1。对该范围内的所有数字继续此过程。以这种方式找到的所有单一数字,计数器加1。
以两个整数start、end作为输入。
函数check_unary(int number)如果传入的值是单一数字则返回true,否则返回false。
函数Unary_range(int start, int end)获取范围变量并返回该范围内单一数字的个数。
将初始计数设置为0。使用for循环,从i=start遍历到end。如果check_unary(i)返回true,则递增计数。
在check_unary(int number)内部,获取临时变量count。
如果数字N为1或7,则返回true。对于所有小于10的其他数字返回false。(number/10 == 0)。
然后在while循环中计算数字平方和。
再次对这样的连续和调用check_unary(int number),直到和变为1。
返回count作为结果。
示例
#include <iostream>
using namespace std;
bool check_unary(int number){
int total;
if (number == 1 ){
return true;
}
else if(number == 7){
return true;
}
else if (number / 10 == 0){
return false;
}
while (number!= 0){
int temp = number % 10;
total = total + temp * temp;
number = number / 10;
}
check_unary(total);
}
int Unary_range(int start, int end){
int count = 0;
for (int i = start; i <= end; i++){
if (check_unary(i) == 1){
count++;
}
}
return count;
}
int main(){
int start = 200, end = 400;
cout<<"Count of Unary Numbers in a Range are: "<<Unary_range(start, end);
return 0;
}输出
如果我们运行上面的代码,它将生成以下输出:
Count of Unary Numbers in a Range are: 31
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP