简体   繁体   English

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

[英]How to check if a int var contains a specific number

How to check if a int var contains a specific number 如何检查int var是否包含特定数字

I cant find a solution for this. 我找不到解决方案。 For example: i need to check if the int 457 contains the number 5 somewhere. 例如:我需要检查int 457是否包含数字5。

Thanks for your help ;) 谢谢你的帮助 ;)

457 % 10 = 7    *

457 / 10 = 45

 45 % 10 = 5    *

 45 / 10 = 4

  4 % 10 = 4    *

  4 / 10 = 0    done

Get it? 得到它?

Here's a C implementation of the algorithm that my answer implies. 这是我的答案所暗示的算法的C实现。 It will find any digit in any integer. 它会找到任何整数的任何数字。 It is essentially the exact same as Shakti Singh's answer except that it works for negative integers and stops as soon as the digit is found... 它与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;
    }
}

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

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);
 }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM