【发布时间】:2017-05-09 06:00:25
【问题描述】:
我们需要检查一个数字中单个数字的出现是否相同。例如对于 2244(2 出现 2 次,4 出现 2 次)。因此,两个数字的出现是相同的。
//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。另外,您能推荐一些优化代码的好方法吗?
【问题讨论】:
-
您的代码为
2222返回 true,因为 2222 是稳定的(2 是唯一出现 4 的数字),您的代码似乎是正确的。 -
Shubh,您能解释一下如何代码不适用于这些数字吗?有没有调试过?
-
Thanx @RajeevSingh ,实际上在我的机器上执行此操作我设置了 count = 0 那就是我遇到了一个错误。
标签: c++ find-occurrences