C++通过数字比较两个数字

C++ comparing two numbers by their digits

本文关键字:数字 两个 比较 C++      更新时间:2023-10-16

我想创建一个函数,每当输入中提供的两个数字由相同的数字组成(没有替换(时,它就会返回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;
}