【发布时间】:2011-06-26 00:50:33
【问题描述】:
如何检查 int var 是否包含特定数字
我找不到解决方案。例如:我需要检查 int 457 是否在某处包含数字 5。
感谢您的帮助;)
【问题讨论】:
-
int值457并不真正“包含”数字5。它的十进制表示可以。
如何检查 int var 是否包含特定数字
我找不到解决方案。例如:我需要检查 int 457 是否在某处包含数字 5。
感谢您的帮助;)
【问题讨论】:
int 值 457 并不真正“包含”数字 5。它的十进制表示可以。
457 % 10 = 7 *
457 / 10 = 45
45 % 10 = 5 *
45 / 10 = 4
4 % 10 = 4 *
4 / 10 = 0 done
明白了吗?
这是我的回答所暗示的算法的 C 实现。它会在任何整数中找到任何数字。它基本上与 Shakti Singh 的答案完全相同,只是它适用于负整数并在找到数字后立即停止......
const int NUMBER = 457; // This can be any integer
const int DIGIT_TO_FIND = 5; // This can be any digit
int thisNumber = NUMBER >= 0 ? NUMBER : -NUMBER; // ?: => Conditional Operator
int thisDigit;
while (thisNumber != 0)
{
thisDigit = thisNumber % 10; // Always equal to the last digit of thisNumber
thisNumber = thisNumber / 10; // Always equal to thisNumber with the last digit
// chopped off, or 0 if thisNumber is less than 10
if (thisDigit == DIGIT_TO_FIND)
{
printf("%d contains digit %d", NUMBER, DIGIT_TO_FIND);
break;
}
}
【讨论】:
int i=457, n=0;
while (i>0)
{
n=i%10;
i=i/10;
if (n == 5)
{
printf("5 is there in the number %d",i);
}
}
【讨论】:
while (i != 0),它也可以处理负数。
将其转换为字符串并检查字符串是否包含字符'5'。
【讨论】: