How to check if a int var contains a specific number

情到浓时终转凉″ 提交于 2020-01-10 03:57:07

问题


How to check if a int var contains a specific number

I cant find a solution for this. For example: i need to check if the int 457 contains the number 5 somewhere.

Thanks for your help ;)


回答1:


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. 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...

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



回答2:


Convert it to a string and check if the string contains the character '5'.




回答3:


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


来源:https://stackoverflow.com/questions/4977456/how-to-check-if-a-int-var-contains-a-specific-number

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!