C++通过数字比较两个数字
C++ comparing two numbers by their digits
我想创建一个函数,每当输入中提供的两个数字由相同的数字组成(没有替换(时,它就会返回true。
例如,543 和 435 应返回 true,10001 和 11000 应返回 true,但 111222 和 122222 应返回 false。
我已经读过一些关于位掩码的东西,但并没有真正理解它,你能帮我吗?
我能想到的最简单的处理方法是使用存储桶。创建一个长度为 10 的std::vector
(每个数字一个(,然后在跨相应数字运行时递增索引。通过比较向量完成:
bool compare_digits(int x, int y) {
std::vector<int> x_vec(10), y_vec(10);
while(x != 0) { //!= instead of > so that we can handle negatives
x_vec.at(x%10)++; //increment whatever digit is in the 1's place
x /= 10; //chop off the 1's place digit
}
while(y != 0) { //repeat for y
y_vec.at(y%10)++;
y /= 10;
}
//check if they had the same digits
return (x_vec == y_vec);
}
两个数字 a 由相同的数字组成,如果每个数字的计数(出现次数(相同。下面是常规基础(模板参数(的一些代码
template<int base=10>
bool compare_digits(int x, int y)
{
// 0 exclude trivial cases
if(x > base*y || y > base*x)
return false;
// 1 count occurrences of digits in x
int count[base]={0};
for(; x; x/=base)
++ count[x%base];
// 2 subtract counts of digits in y, if result < 0: return false
for(; y; y/=base)
if(--count[y%base] < 0)
return false;
// 3 check that count[]==0
for(int i=0; i!=base; ++i)
if(count[i]) return false;
return true;
}
相关文章:
- C++通过数字比较两个数字
- 将向量之间的数字放在另一个向量之间<vector>>如果两个数字的差值为 1
- 在 txt 文件中显示前两个数字的程序
- 两个有符号数字之间的距离
- 形成一个斐波那契三角形,使得每个数字是上面左对角线或右对角线上两个数字的总和
- 将数字表示为两个三角形数字的总和
- 两个数字的对称配对功能
- 无法理解代码背后的逻辑,这是在两个给定数字之间生成素数的优化问题
- 查找中间两个数字的正则表达式的匹配项
- 使用C++具有两个数字的最短路径算法.(C++)
- 将两个数字添加为链表
- C++ 分段错误:11 错误,同时编码将两个数字相加的链接列表
- 如何对两个 4 位数字进行乘法,将它们视为 C++ 中的多项式
- 在手臂氖中高效计算两个不同的数字
- 如何在 c++ 中添加两个大的双精度数字
- 我应该如何使用remove_if删除两个数字范围内的元素
- C++显示两个区间之间的数字的程序检查一个数字是否可以表示为两个素数的总和
- 是否有任何内置函数可以检查给定的两个数字在给定整数数组中的顺序是否相同?
- 如何在两个不同大小的向量中找到公共数字
- 如何使用C++中不是文字的变量在数字中显示单引号和两个引号?假设 6'2" 英尺