Codeforces 1560A Dislike of Threes 不喜歡數字3

難易度 : 800

英文原文如下

Polycarp doesn’t like integers that are divisible by 3 or end with the digit 3 in their decimal representation. Integers that meet both conditions are disliked by Polycarp, too.

Polycarp starts to write out the positive (greater than 0) integers which he likes: 1,2,4,5,7,8,10,11,14,16,…. Output the k-th element of this sequence (the elements are numbered from 1).

中文翻譯

Polycarp 不喜歡可以被3整除的整數以及個位數是3的整數,他也不喜歡同時符合這兩個條件的整數。

Polycarp 開始寫出他喜歡的正整數: 1,2,4,5,7,8,10,11,14,16,….

輸出這個序列的第 k 個元素(元素從1開始編號)。

輸入

The first line contains one integer t (1≤t≤100) — the number of test cases. Then t test cases follow.

Each test case consists of one line containing one integer k (1≤k≤1000).

第一行包含了一個整數 t (1≤t≤100) — 測試案例的數量。接下來有 t 個測試案例。

每一個測試案例

輸出

For each test case, output in a separate line one integer x — the k-th element of the sequence that was written out by Polycarp.

針對每一個測試案例,輸出用行分隔的整數 x — Polycarp所寫序列的第 k 個元素

範例

輸入10
1
2
3
4
5
6
7
8
9
1000
輸出1
2
4
5
7
8
10
11
14
1666

解題思路

在我們的解法中,我們會使用一個while迴圈以及計數器來判斷現在數到第幾個數字了

C# 解決方案

方案1

int t = int.Parse(Console.ReadLine());

for(int i=0; i<t; i++){
    int k = int.Parse(Console.ReadLine());
    int cnt = 0;
    int num = 1;
    while(true){
        //numbers he dislike
        if(num%3==0||num%10==3){
            num+=1;
            continue;
        }
        
        //numbers he like
        cnt+=1;
        
        if(cnt==k){
            Console.WriteLine(num);
            break;
        }
        
        num+=1;
    }
}

Java 解決方案

方案1

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int t = Integer.parseInt(scanner.nextLine());

        for (int i = 0; i < t; i++) 
        {
            int k = Integer.parseInt(scanner.nextLine());
            int cnt = 0;
            int num = 1;
            while(true){
                //numbers he dislike
                if(num%3==0||num%10==3){
                    num+=1;
                    continue;
                }
                
                //numbers he like
                cnt+=1;
                
                if(cnt==k){
                    System.out.println(num);
                    break;
                }
                
                num+=1;
            }
        }
    }
}
Klook.com

Python3 解決方案

方案1

t = int(input())

for i in range(t):
    k = int(input())
    cnt = 0
    num = 1
    
    while(True):
        if(num%3==0 or num%10==3):
            num+=1
            continue
    
        cnt+=1
        
        if(cnt==k):
            print(num)
            break
        
        num+=1

結論

🧡如果文章有幫上你的忙,那是我的榮幸

🧡收藏文章或幫我點個廣告,那都是對我的支持

✅如有任何疑問,歡迎透過留言或messenger讓我知道 !

題目連結 : Problem – 1560A – Codeforces

一些其他的Codeforces文章

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *