如何检查int var是否包含特定数字

c57*_*272 6 c int numbers char

如何检查int var是否包含特定数字

我找不到解决方案.例如:我需要检查int 457是否包含数字5.

谢谢你的帮助 ;)

mat*_*fin 14

457 % 10 = 7    *

457 / 10 = 45

 45 % 10 = 5    *

 45 / 10 = 4

  4 % 10 = 4    *

  4 / 10 = 0    done
Run Code Online (Sandbox Code Playgroud)

得到它?

这是我的答案所暗示的算法的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;
    }
}
Run Code Online (Sandbox Code Playgroud)


Yhr*_*hrn 4

将其转换为字符串并检查该字符串是否包含字符“5”。