Codeforces 271A Beautiful Year 漂亮的年份

難易度 : 800

英文原文如下

It seems like the year of 2013 came only yesterday. Do you know a curious fact? The year of 2013 is the first year after the old 1987 with only distinct digits.

Now you are suggested to solve the following problem: given a year number, find the minimum year number which is strictly larger than the given one and has only distinct digits.

中文翻譯

2013年就像昨天來的一樣。你知道一個有趣的事實嗎,2013年是1987年後的第一個有4個不同的數字的年份。

現在你被建議來解決以下的問題 : 給予一個年份,找到大於它最小的擁有4個唯一且不同(distinct)的年份。

輸入

The single line contains integer y (1000 ≤ y ≤ 9000) — the year number.

唯一的一行包含了整數  y (1000 ≤ y ≤ 9000) — 年份。

輸出

Print a single integer — the minimum year number that is strictly larger than y and all it’s digits are distinct. It is guaranteed that the answer exists.

印出一個整數 — 最小的大於輸入年份的擁有4個不同數字的年份,答案保證存在。

範例

輸入1987
輸出2013
輸入2013
輸出2015

解題思路

在這種不確定要查幾次的狀況下,用 while 來迴圈會是個好主意。

C#解決方案

方案1

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

while (true)
{
    year++;
    if (year.ToString().Distinct().Count() == year.ToString().Length)
    {
        Console.WriteLine(year);
        break;
    }
}

在C#的解法中,判斷用的是LINQ的Distinct之後Count,要是數字等於本來的長度,就代表每個數字都是唯一的,就可以印出來。

Java解決方案

方案1

import java.util.Scanner;
import java.util.HashSet;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int year = scanner.nextInt();
        boolean loop = true; 
         
        while (loop) {
            year++;
            
            HashSet<Character> hSet = new HashSet<>();
            char[] digits = Integer.toString(year).toCharArray();
            
            for (char digit : digits) {
                if(!hSet.contains(digit))
                {
                    hSet.add(digit);
                }
            }
            
            if (hSet.size() == digits.length) {
                System.out.println(year);
                loop = false;
            }

        }
    }
}

Java就比較麻煩了一點,在這裡用了HashSet來儲存以及判斷是否存在 (while 中的 for loop)


結論

題目提到了2013年… 仔細一想好久以前了啊啊啊,看來這是一題年紀跟恐龍差不多大的題目呢~

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

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

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

題目連結 : Problem – 271A – Codeforces

一些其他的Codeforces文章

發佈留言

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