[Codility] Lesson5.CountDiv (C++)

2021. 2. 23. 21:00·코딩 테스트
728x90

🔮문제

Write a function:

int solution(int A, int B, int K);

that, given three integers A, B and K, returns the number of integers within the range [A..B] that are divisible by K, i.e.:

{ i : A ≤ i ≤ B, i mod K = 0 }

For example, for A = 6, B = 11 and K = 2, your function should return 3, because there are three numbers divisible by 2 within the range [6..11], namely 6, 8 and 10.

Write an efficient algorithm for the following assumptions:

  • A and B are integers within the range [0..2,000,000,000];
  • K is an integer within the range [1..2,000,000,000];
  • A ≤ B.

 

🔮풀이

1. A=B 일 경우

  A%K 가 0이면 1 리턴, 아니면 0을 리턴한다.

2. A != B일 경우

  (B를 K로 나눈 몫 - A를 K로 나눈 몫 + 1) 를 하면 그 사이에 K로 나눠지는 값들을 구할 수 있다.


🔮코드

 #include <algorithm>

int solution(int A, int B, int K) {
    if(A==B){
        if(A%K==0){
            return 1;
        }
        else{
            return 0;
        }
    }
    else{
        int start = 0;
        for(int i=A; i<=B; i++){
            if(i%K == 0){
                start = i;
                break;
            }
        }
        return B/K - start/K + 1;
    }
}

 

728x90

'코딩 테스트' 카테고리의 다른 글

[Codility] Lesson4. Brackets  (0) 2021.03.03
[프로그래머스] 괄호변환 (C++)  (0) 2021.03.02
[Codility] Lesson4. FrogRiverone (C++)  (0) 2021.02.23
[Codility] Lesson3. TapeEquilibrium (C++)  (0) 2021.02.23
[Codility] Lesson3. PermMissingElem (C++)  (0) 2021.02.23
'코딩 테스트' 카테고리의 다른 글
  • [Codility] Lesson4. Brackets
  • [프로그래머스] 괄호변환 (C++)
  • [Codility] Lesson4. FrogRiverone (C++)
  • [Codility] Lesson3. TapeEquilibrium (C++)
zoodi
zoodi
IT/개발 관련 지식을 기록하는 블로그입니다.
  • zoodi
    오늘의 기록
    zoodi
  • 전체
    오늘
    어제
    • 분류 전체보기
      • 후기
        • 컨퍼런스
        • 일상리뷰
      • 금융경제
        • 뉴스
        • 금융IT용어
        • 경제 및 부동산
      • 코딩 테스트
      • 스터디
        • JAVA
        • Kotlin
        • Spring
        • React, Nextjs
        • 인공지능 AI
        • Cloud & k8s
        • Kafka
        • Database
        • Network
        • Algorithm
        • Hadoop
        • LINUX
        • R Programming
        • 기타 (소공, 보안)
      • 도서
      • 기타
  • 블로그 메뉴

    • 홈
    • 스터디
    • 금융경제
    • 후기
    • 기타
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    쿠버네티스
    코테
    코딜리티
    pythoncodingtest
    java
    카카오코테
    코테공부
    자바
    코딩테스트
    이분탐색
    금융용어
    CodingTest
    리트코드
    프로그래머스
    네트워크
    C++
    자료구조
    kafka
    MySQL
    Kotlin
    db
    LeetCode
    알고리즘
    springboot
    스프링
    Spring
    코딩
    codility
    Python
    스프링부트
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.4
zoodi
[Codility] Lesson5.CountDiv (C++)
상단으로

티스토리툴바