We need to check whether the occurrence of an individual digit in a number is same or not.For e.g. for 2244 (2 occur 2 times and 4 occur 2 times).Therefore, occurrence of both digits are same.
//This will return true if occurrence of individual digit in
//a number is same else false
bool stable(int no)
{
vector<int> v1;
int k , count = 1;
int arr[10];
//Initializing all arr[] -> 0
for(int k = 0 ; k < 10 ;k++)
{
arr[k] = 0;
}
while(no != 0)
{
k=no%10;
arr[k]++;
no=no/10;
}
for(int i = 0 ; i < 10 ; i++)
{
if(arr[i] != 0)
{
v1.push_back(arr[i]); //storing count of individual digits
}
}
vector<int>::iterator it , it2;
for(it = v1.begin()+1 ,it2 = v1.begin(); it != v1.end() ; it++,it2++)
{
if(*it == *it2) //if all the values are same return true else false
{
count++;
}
}
if(count == v1.size()) return true;
return false;
}
但此代码不适用于 2222,1111,444。另外,您能推荐一些优化代码的好方法吗?
最佳答案
我认为你让这件事变得比需要的更难(或者我严重误解了这个问题,这种情况经常发生)。
假设要求是指定的:给定一个非零正值,如果所有数字出现的频率相同,包括 1,则数字是合格的(例如:1122、2222、1234 都合格,因为没有数字具有更高的频率频率高于任何其他)。
算法很简单:
- 任何小于 10 的值都可以快速返回;一位数立即合格。
- 构建模数残差计数器数组。
- 找到数组中的第一个非零值
- 从那时起,找到与 (4) 中的值不匹配的第一个非零值。如果您到达序列的末尾而没有发现这种差异,则原始数字中的所有数字必须具有相同的计数。
总的来说,复杂度是输入数字的以 10 为底的对数加上恒定大小数组(10 个元素)的单次扫描。
示例代码
#include <algorithm>
#include <iterator>
bool stable(unsigned value)
{
if (value < 10) // single digit only, including zero
return true;
unsigned ar[10]={0};
do { ++ar[value%10]; }
while (value /= 10);
auto it = std::find_if(std::begin(ar), std::end(ar),
[](auto n) { return n != 0; });
return std::find_if(std::next(it), std::end(ar),
[it](auto n){ return n && (n != *it);}) == std::end(ar);
}
如果最终为 1(例如:1234、102938 就是这样的示例),您始终可以通过保留最大位数并在不进行查找操作的情况下继续执行此操作。我将把它留作练习,供您进行基准测试以确定是否有任何性能优势。老实说,我怀疑会有。
关于c++ - 检查数字中单个数字的出现次数是否相同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43862177/