鉴于a和b之间的数字范围,我需要找到所有具有重复数字的数字。它们不必是连续的重复数字-例如121将被视为这些数字之一。我已经编码了向量列表本身的输入-我只是不知道如何分析该向量中每个单独项目的数字。
#include <iostream>
#include <vector>
using namespace std;
int main(){
//variables
int a, b, i = 0; // a & b inputs, i for iterating
//entering number range
cout << "Enter the first number" << endl;
cin >> a;
cout << "Enter the second number" << endl;
cin >> b;
//making a vector to contain numbers between a and b
vector<int> listofnums((b-a)+1);
int initialvalue = a;
while (i <= (b-a)) {
listofnums[i] = initialvalue;
initialvalue++;
i++;
}
//printing the completed vector
for ( const auto &item : listofnums ){
std::cout << item << ' ';
}
std::cout << '\n';
//analyzing the digits of each item in the vector
//code for finding repeating digits here
return 0;
}
您可以将十进制数的最低(最低有效)数字除以10后的余数;在C++
中,这很容易使用模运算符(%
)完成。因此,给定integer变量a
,其值为123
,语句int b = a % 10;
将3
分配给b
。
现在,通过运行一个循环,在该循环中,我们将“测试”数字顺序除以10(直到达到零),我们可以获得每个数字的值。如果我们保留bool
值的数组,并在找到给定数字时将每个值设置为true
,则可以快速检测到重复的数字。
因此,此功能将完成工作:
bool HasRepeatDigit(int x)
{
bool hasDigit[10] = {false, false, false, false, false, false, false, false, false, false};
while (x > 0) {
int digit = x % 10;
if (hasDigit[digit]) return true; // We already have this digit!
hasDigit[digit] = true; // Flag the digit we just found
x /= 10; // Divide by 10, to move onto the next digit
}
return false; // If we get here, there is no repeat digit!
}
随时要求进一步的解释和/或澄清。
此外,您可以使用listofnums
函数(在[std::iota][1]
标头中定义)减少填充<numeric>
向量的代码:
#include <numeric>
//...
std::iota(begin(listofnums), end(listofnums), a);