Determine if a number contains a digit for class assignment

久未见 提交于 2021-01-16 04:02:39

问题


Write a function named containsDigit that determines if a number contains a particular digit.

The header should look like:

bool containsDigit(int number, int digit);

If number contains digit, then the function should return true. Otherwise, the function should return false.

Input: 
147 9

Output: 
false

I don't know why I always get false when I write like this:

bool containsDigit(int number, int digit);

int main() {
  double con;
  int number, digit;
  cout << "Input a number and a digit:\n";
  cin >> number >> digit;
  con = containsDigit(number, digit);
  cout << con;
  return 0;
}

bool containsDigit(int number, int digit) {
  int a(0), b;
  b = number;
  while (number > 0) {
    a = a + 1;
    number = number / 10;
  }
  cout << a;
  while (a > 1) {
    a = a - 1;

    if (b / pow(10, a) == digit) {
      cout << "true\n";
      break;
    } else {
      if (a == 1)
        cout << "false\n";
      else
        cout << "";
    }
    b = b % pow(10, a);
  }
}

回答1:


Breaking the problem down is the key do not jump to code, start off by asking yourself, how do I extract digits?

Use the % operator with 10. That's your current number % 10. Why 10? and not any other number? - We need to get the remainder after division which is what the modulo operator does any other number doesn't cut it, try it on a calculator.

So far so good, now what else do you need to do? You need to move forward in your search and compare the remaining digits. 147 % 10 already gave you 7 and you want to look at 14, to separate 14 from 7 you divide by 10 and get the remaining part not including 7. You continue your scan till you either find the number or are out of numbers which is the result. There is a problem here, a follow up, does your code work for negative numbers? I will leave that up to you to figure out.

We are left with the following code,

bool containsDigit(int number, int digit)
{
    while (number != 0)
    {
        int curr_digit = number % 10;
        if (curr_digit == digit) return true;
        number /= 10;
    }

    return false;
}


来源:https://stackoverflow.com/questions/46803064/determine-if-a-number-contains-a-digit-for-class-assignment

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