c - Why am I not able to print output as number of unique digits between range n1 to n2?
问题描述
Given two non-negative integers n1 and n2, where n1<n2. The task is to find the total number of integers in the range [n1, n2](both inclusive) which have no repeated digits.
I have worked out the logic but the output is still not right.
int main(void) {
int n1, n2, count = 0, num;
scanf("%d %d", & n1, & n2);
for (int i = n1; i <= n2; i++) {
int num = i;
bool m[10] = {
false
};
while (num > 0) {
if (m[num % 10] == true) {
break;
m[num % 10] = true;
num = num / 10;
}
}
}
if (num == 0) {
count++;
}
printf("%d", count);
return 0;
}
解决方案
It is very hard to read your code. You need to indent it properly - it will help you a lot.
- Use functions.
- Not always
bool
is the best choice.
int hasRepeating(long long num)
{
int dig[10] = {0,};
do
{
if(++dig[abs((int)(num % 10))] > 1) return 1;
num /= 10;
}while(num);
return 0;
}
size_t findNumber(long long num1, long long num2)
{
size_t num = 0;
for(long long x = num1; x <= num2; x++)
{
if(!hasRepeating(x)) num++;
}
return num;
}
int main(void)
{
int num1 = -9000, num2 = 100000;
printf("Number of numbers with not repeated digits in range <%d, %d> = %zu\n", num1, num2, findNumber(num1, num2));
}
推荐阅读
- python - 用 Panda 构建奇数行的矩阵
- c++ - error c2679 binary '=' no operator found which takes right hand operand of type std::tuple
- angular - How to display real time data thorugh Angular data table?
- python - TypeError: read_excel() got an unexpected keyword argument 'keep_date_col'
- rust - 测试在工作区中的行为与作为独立项目不同
- asp.net - 无法序列化会话状态“System.Web.SessionState.HttpSessionState”
- c++ - GCC C++ 链接错误:未定义对“WinMain@16”的引用
- telephony - 在 Bitrix24 中收听代理的呼叫
- c++ - 在 QT 中以(快速)恒定速率旋转 3D 对象
- asp.net - ASP.NET Web 窗体在单击 50 次后崩溃