21xrx.com
2024-09-20 05:50:12 Friday
登录
文章检索 我的文章 写文章
如何在C++中判断一个数是否含有特定数字?
2023-06-27 12:59:38 深夜i     --     --
C++ 判断 含有特定数字

在C++中,判断一个数是否含有特定数字可以采用以下方法。

方法1:将数转为字符串,查找特定数字

将数转为字符串,然后可以用字符串查找函数find()查找是否含有特定数字。代码如下:


#include <iostream>

#include <string>

using namespace std;

bool containNum(int num, int target) {

  string str = to_string(num);

  string target_str = to_string(target);

  if (str.find(target_str) != string::npos)

    return true;

  

  return false;

}

int main() {

  int num = 12345;

  int target = 3;

  if (containNum(num, target))

    cout << "num contains target: " << target << endl;

   else

    cout << "num does not contain target: " << target << endl;

  

  return 0;

}

方法2:循环取每一位数并判断

依次取出num的每一位数,然后和target进行比较。代码如下:


#include <iostream>

using namespace std;

bool containNum(int num, int target) {

  while (num > 0) {

    if (num % 10 == target)

      return true;

    

    num /= 10;

  }

  return false;

}

int main() {

  int num = 12345;

  int target = 3;

  if (containNum(num, target))

    cout << "num contains target: " << target << endl;

   else

    cout << "num does not contain target: " << target << endl;

  

  return 0;

}

以上两种方法都可以判断一个数是否含有特定数字,选择哪种方法取决于具体的应用场景和需求。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复