Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
707 views
in Technique[技术] by (71.8m points)

c - How to check if a int var contains a specific number

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
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;
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...