只有在没有重复数字的情况下才打印数字

Print a number only if no digits are repeated

本文关键字:数字 情况下 打印      更新时间:2023-10-16

我正在编写一个程序,该程序的输出要求打印的数字在中没有重复的整数

即不会打印122161998等
但它可以打印任何其他数字,如123345742..等

我该怎么做?谢谢

我会使用"位数组"来跟踪数字:这更像是一种"C"式的解决方法。。。

int number_orig = ...,
    number = number_orig;
    bits = 0;
bool duplicate = false;
while (number != 0 && !duplicate)
{
 int digit = number % 10;
 if (bits & (1 << digit))
   duplicate = true;
 bits |= (1 << digit);
 number /= 10;
}
if (!duplicate)
  cout << number_orig;

C语言兼容的解决方案是将数字转换为字符串,并保持数字的频率计数,如果存在重复,则返回true,例如:

int has_duplicate_digit(char * s) {
  char digit_count[10] = {0,0,0,0,0,0,0,0,0,0};
  for (int i=0; i<strlen(s); i++) {
    if ('0' <= s[i] && s[i] <= '9') {
      if (++digit_count[s[i]-'0'] > 1) return 1; // true
    }
  }
  return 0; // false
}

[Edit]您还可以使用位集而不是int数组来节省一些字节(可能还需要一些时间)。例如:

#include <stdint.h>
int has_duplicate_digit2(char * s) {
  uint16_t digit_count = 0;
  for (int i=0; i<strlen(s); i++) {
    if ('0' <= s[i] && s[i] <= '9') {
      uint16_t bit = 1 << (s[i] - '0');
      if (digit_count & bit) return 1; // true
      digit_count |= bit;
    }
  }
  return 0; // false
}

您可以创建一个std::set,循环数字,将它们添加到集合中,并查看数字的数量是否等于集合的大小。如果是,则不会重复任何数字。

如果你怀疑大多数数字都不符合要求,你可以在每次插入后检查该数字是否真的添加到了集合中,如果不是,则立即拒绝该数字。

一个简单的基于字符串的解决方案:转换、排序、uniquify、计数:

#include <string>
#include <algorithm>
#include <iostream>
for (unsigned int i = 0; ; ++i)
{
    std::string sorig = std::to_string(i), suniq = sorig;
    std::sort(suniq.begin(), suniq.end());
    if (std::unique(suniq.begin(), suniq.end()) == suniq.end())
    {
        std::cout << sorig << std::endl;
    }
}

只需将数字转换为字符串(itoa),就可以更容易地解决核心任务。

将数字转换为字符串,并设置代表1 << ( digit - '0' )的10位(全部为零),然后可以检查每个数字以前是否见过,如果见过,则返回。否则设置该位。

相关文章: