只有在没有重复数字的情况下才打印数字
Print a number only if no digits are repeated
我正在编写一个程序,该程序的输出要求打印的数字在中没有重复的整数
即不会打印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位(全部为零),然后可以检查每个数字以前是否见过,如果见过,则返回。否则设置该位。
相关文章:
- 在C++不适用于猜数字游戏的情况下再次播放选项
- 在不添加进位的情况下添加数字的C++程序
- 如何在不使用 C++ 中的数组或函数的情况下查找 N 位数字的所有排列
- C++在不使用pow或循环的情况下计算一个数字的幂
- 如何在不导致堆栈溢出的情况下计算非常大的数字和很小的 HCF.我正在使用欧几里得算法
- 我可以在不指定数字分布的情况下使用随机生成器吗?
- 在没有比较运算符的情况下查找 2 个数字之间的最小值
- 有没有办法将数字作为字符串,并在不使用浮点数或双精度数的情况下将其四舍五入到确切的位数
- 使用default_random_engine作为类成员,而没有类的情况下会产生不同的数字(同一种子)
- 如何在不丢失第一位数字的情况下打印出双精度值
- 在不重新编译源代码的情况下更改C++(C)程序中定义的数字
- 如何在给定特定公式的情况下将用户输入的一些数字相加
- 在不使用递归的情况下将 FFT 应用于两个非常大的数字的乘法
- 如何在不使用数学的情况下知道一个数字是否是回文
- 在不进行线性搜索的情况下,在非常大的数组中找到比给定数字更小的数字
- 如何在不使用堆栈或数组的情况下从INT中提取每个数字?(C )
- 如何在无法访问 vblank 的情况下实现平均 60(或 30,或其他数字)FPS?
- 在没有字符串或字符帮助的情况下查找数字的反面(例如:2500 reverse 0025)
- 有没有办法在不分配变量的情况下将字符串连接到数字
- 在没有外部库的情况下C++计算大量数字