我有一个区间(m,n),我必须打印出所有具有不同数字的数字。我写了这个,但它只适用于 2 位数字。我只是不知道如何让它适用于除 2 位数字之外的任何数字。我想,如果我添加的 for 循环与我的数字的数字一样多,它就会起作用,但是没有指定间隔(m,n),所以它必须是可靠的。我花了 6 个小时试图自己解决这个问题,但我实在受够了。
输入97,113; 输出 97,98,102,103,104,105,106,107,108,109 数字 99,100,101,110+ 不会被打印,因为它们有 2 位数字 相同。
#include<conio.h>
#include<math.h>
#include<stdio.h>
int main()
{
int m,n,test,checker=0;
scanf("%d%d",&m,&n);
if(m>n)
{
int holder=n;
n=m;
m=holder;
}
for(int start=m;start<=n;start++)
{
int itemCount=floor(log10(abs(start)))+1;
int nums[itemCount];
int index=0;
test=start;
do
{
int nextVal = test % 10;
nums[index++]=nextVal;
test = test / 10;
}while(test>0);
for (int i = 0; i < itemCount - 1; i++)
{ // read comment by @nbro
for (int j = i + 1; j < itemCount; j++)
{
if (nums[i] == nums[j])
{
checker++;
}
}
if(checker==0)printf("%d ",start);
}
checker=0;
}
}
最佳答案
由于您将其标记为 C++,因此这是一个非常简单的解决方案,在循环中使用简单的模数和除法。没有完成到字符串的转换。
#include <iostream>
#include <bitset>
bool is_unique_digits(int num)
{
std::bitset<10> numset = 0;
while (num > 0)
{
// get last digit
int val = num % 10;
// if bit is on, then this digit is unique
if (numset[val])
return false;
// turn bit on and remove last digit from number
numset.set(val);
num /= 10;
}
return true;
}
int main()
{
for (int i = 97; i <= 113; ++i)
{
if (is_unique_digits(i))
std::cout << i << "\n";
}
}
is_unique_digit
函数只是获取数字,并通过获取数字中的最后一位数字来重复提取数字。然后测试该数字以查看相同的数字是否出现在位集中。如果该号码已存在,则立即返回 false
。
如果该数字不在位集中,则与该数字对应的位将“打开”,并且该数字除以 10(有效地从数字中删除最后一位数字)。如果循环完成,则返回 true
。
关于c++ - X 元素数组中的重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41509997/