输入左限号、右限号和要计数的数字。此代码仅适用于整数,即从0到n。此代码返回在给定范围内出现的数字n的数目。请检查此代码并提出改进建议。
#include <iostream>
int count_n(int l, int r, int n)
{
if (r <= l)
{
std::cerr << "Right limit must greater then left limit\n";
return 0;
}
if (l < 0)
{
std::cerr << "Only positive integers\n";
return 0;
}
int count = 0;
for (int i = l; i <= r; ++i)
{
int i_copy = i;
while (i_copy != 0)
{
if (i_copy % 10 == n)
{
count++;
}
i_copy = i_copy / 10;
}
}
return count;
}
int main()
{
int left_limit, right_limit, num;
std::cout << "Enter left limit, right limit and the number(Only positive numbers)\n";
std::cin >> left_limit >> right_limit >> num;
int result = count_n(left_limit, right_limit, num);
std::cout << result << "\n";
}输出:
Enter left limit, right limit and the number(Only for positive numbers)
1 20 0
2发布于 2019-10-27 16:34:13
除了这之外,您还应该指定n ( digit )的验证。另外,将验证分组为单独的功能可能更好。
void check_input(int min_left, int max_right, int digit) {
if (max_right <= min_left)
throw std::invalid_argument("right is <= left, expected right > left");
if (min_left < 0)
throw std::invalid_argument("left < 0, expected left > 0");
if (digit <= 0)
throw std::invalid_argument("digit <= 0");
//throw std::invalid_argument("number <= 0");
if (digit > 9)
throw std::invalid_argument("digit > 9");
////number:
//if (digit > max_right)
// throw std::invalid_argument("number > right limit");
}
int count_digit_entries(int min_left, int max_right, int digit) {
//...
}
int main() {
int left_limit, right_limit, num;
std::cout << "Enter left limit, right limit and the number(Only positive numbers)\n";
std::cin >> left_limit >> right_limit >> num;
check_input(left_limit, right_limit, num);
int result = count_digit_entries(left_limit, right_limit, num);
std::cout << "\nTotal: " << result << "\n";
}你可能不仅想要找到数字,还想找到一个完整的数字。
//...
#define DEBUG
#ifdef DEBUG
#define debug(x) x
#else
#define debug(x)
#endif
int count_digit_entries(int min_left, int max_right, int search_number) {
int count = 0;
int mod = 10;
while(search_number / mod > 0) mod = mod * 10; // 279 -> 1000
for (int current_number = min_left, right = max_right; current_number < right; ++current_number) {
int copied_current_number = current_number; // 542793
while (copied_current_number >= search_number) {
// 542793 - 279 % 1000 >0
// 54279 - 279 % 1000 =0
if ( ( (copied_current_number - search_number) % mod ) == 0 ) {
debug(std::cout << current_number << " ");
++count;
};
copied_current_number = copied_current_number / 10;
// 542793 -> 54279
};
};
return count;
};输出:
Enter left limit, right limit and the number(Only positive numbers)
0 1000 25
25 125 225 250 251 252 253 254 255 256 257 258 259 325 425 525 625 725 825 925
Total: 20https://codereview.stackexchange.com/questions/231371
复制相似问题