작성일 :

문제 링크

30224번 - Lucky 7

설명

정수 n이 주어질 때, 숫자 7을 포함하는지와 7로 나누어 떨어지는지에 따라 0부터 3까지의 값을 출력하는 문제입니다.


두 조건 모두 만족하지 않으면 0, 7로만 나누어지면 1, 7을 포함하기만 하면 2, 둘 다 만족하면 3을 출력합니다.


접근법

먼저 n을 문자열로 변환하여 7이 포함되어 있는지 확인합니다. 이후 n을 7로 나눈 나머지가 0인지 확인합니다.


두 조건의 조합에 따라 결과가 결정됩니다. 두 조건 모두 거짓이면 0, 나누어지기만 하면 1, 포함하기만 하면 2, 둘 다 참이면 3을 출력합니다.


Code

C#

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
using System;

class Program {
  static void Main() {
    var n = int.Parse(Console.ReadLine()!);
    var hasSeven = n.ToString().Contains('7');
    var divisible = (n % 7 == 0);

    var ans = 0;
    if (!hasSeven && divisible) ans = 1;
    else if (hasSeven && !divisible) ans = 2;
    else if (hasSeven && divisible) ans = 3;

    Console.WriteLine(ans);
  }
}

C++

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <bits/stdc++.h>
using namespace std;

int main() {
  ios::sync_with_stdio(false);
  cin.tie(nullptr);

  int n; cin >> n;
  string s = to_string(n);
  bool hasSeven = s.find('7') != string::npos;
  bool divisible = n % 7 == 0;

  int ans = 0;
  if (!hasSeven && divisible) ans = 1;
  else if (hasSeven && !divisible) ans = 2;
  else if (hasSeven && divisible) ans = 3;

  cout << ans << "\n";

  return 0;
}

Tags: 30224, BOJ, C#, C++, 구현, 백준, 수학, 알고리즘

Categories: ,