【问题标题】:Five-digit number is given. Determine whether the number contains at least two identical digits [closed]给出五位数字。确定数字是否包含至少两个相同的数字[关闭]
【发布时间】:2021-12-15 10:38:35
【问题描述】:

给出五位数字。判断数字是否至少包含两个相同的数字

这是我的代码,用 C++ 编写:

#include <iostream>
using namespace std;

int main()
{
    int n,a,b,c,d,f;
    cin >> n;
    a=n/10000;
    b=n/1000%10;
    c=n/100%10;
    d=n/10%10;
    f =n%10;
    if(a==b && c==d && b!=c ||
       a==c && b==d && c!=b ||
       a==d && b==c && d!=b ||
       a==f && f==b && f!=d )
        cout << "YES";
    else
        cout << "NO";
    return 0;
}

这行不通…… 有人可以帮忙吗?

【问题讨论】:

  • 我投票结束这个问题,因为没有提出任何问题。
  • 你的问题是什么?
  • @Emily,请描述您面临的问题以及您的问题。
  • 您是否考虑过另一种方法,例如将数字读取为std::string,然后用数字作为键和出现次数作为值填充std::map? (或者老派,只需使用 10 个 char 的数组作为 频率数组 并将数字映射到每个索引)
  • 您可以在此处How to remove duplicate char in string in C 找到有关使用频率阵列的更多信息

标签: c++ digits


【解决方案1】:

这应该可以工作

#include <iostream>
using namespace std;

int main(){
    int n, a, b, c, d, f;
    cin >> n;

    a = n / 10000;
    b = n / 1000 % 10;
    c = n / 100 % 10;
    d = n / 10 % 10;
    f = n % 10;

    if( a==b || b==c || c==d ||
        a==c || b==d || c==f ||
        a==d || b==f || d==f ||
        a==f )
        cout << "YES";
    else
        cout << "NO";
    
    return 0;
}

【讨论】:

  • 你能解释一下你改变了什么吗?
  • 我只是更改了“if 条件”。请将此与问题中的代码进行比较。将有助于更好地理解!
【解决方案2】:

此代码适用于整数输入

#include<bits/stdc++.h>
using namespace std;

int main(){
  int n;
  vector<int>vec;
  set<int>s;
  cin>>n;
  while(n!=0)
  {
    int re=n%10;
    n=n/10;
    vec.push_back(re);
    s.insert(re);
  }
  if ((vec.size()-s.size())>=1)
    cout<<"YES"<<endl;
  else
    cout<<"NO"<<endl;
  return 0;


}

【讨论】:

    【解决方案3】:

    将输入读取为字符串,然后使用表格扫描重复的整数。

    std::string n;
    int digits[10] = {0}; // the number of occurrences of all digits from 0..9
    bool dupes = false;
    
    cin >> n;
    
    for (char c : n) {
       if ((c >= '0') && (c <= '9')) {
           int index = c - '0';
           digits[index]++;
           if (digits[index] > 1) {
               dupes = true;
           }
       }
    }
    
    if (dupes) {
       cout << "YES";
    }
    else {
       cout << "NO";
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-06-28
      • 2013-08-11
      • 2022-11-16
      • 1970-01-01
      • 2010-12-28
      • 2012-08-26
      • 1970-01-01
      • 2014-11-16
      相关资源
      最近更新 更多