开发者

C - need to detect presence of digit in a number (hw)

I'm trying to write a function that'll detect if a digit is found in a number:

// returns 1 if source contains num, 0 otherwise
int contains_num(source, num);

for example, contains_num(12345, 3) returns 1 and contains_num(12345, 6) returns 0.

I'm not sure how to go a开发者_JAVA百科bout solving this. Probably can't use pointers, arrays and such.

Any ideas? thanks.


Since this is homework, I don't want to give you the entire answer right away. Instead, I'll ask a series of questions, and let you answer in the comments, so I'll simply be guiding you to the correct answer rather than giving it to you outright.

So, you have a number, and you want to break it down into individual digits. Can you think of a way of extracting one digit from the number, say, the last one? Think about what each digit represents, and how you might be able to isolate one digit from the rest of them.


An alternative way of looking at the problem is:

  • Does the string representation of the number contain a specific digit?

It is relatively easy to convert the number to a string; there are string searching functions to find whether a specific character appears in the string.

And this has the merit of working on negative numbers whereas some of the suggestions I've seen fail on negative numbers (and most of the rest do not address the issue explicitly). (Question for you: why?)


This should work:

int Contains_Num(int source, int num)
{
  if (source == 0 && num == 0) return 1;

  int tmpSource = source;
  while (tmpSource != 0)
  {
    if (tmpSource % 10 == num) return 1;
    tmpSource /= 10;
  }
  return 0;
}


Your answer is dependent on the base a number is represented in. For example, the number 255 contains 5 when written in base 10, but in base 16, it does not. Your base seems to be 10.

So what you want to do is to look at the last digit of a number, and see if it is the digit you want. The last digit can be easily found using the modulo operator (%). If it is the digit you want, you're done. If not, and if there are more digits, you can discard the last digit and repeat the process again for the number obtained by dividing the original number by 10 and discarding the fractional part. In C, the division operator, /, does this for you automatically if both the operands of it are of integer type.

When you run out of digits because division gives you 0, you are sure that the number doesn't contain the digit you wanted.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜