Codeforces 339A Helpful Maths 有用的數學 – 翻譯與解答

難易度 : 800

英文原文如下

Xenia the beginner mathematician is a third year student at elementary school. She is now learning the addition operation.

The teacher has written down the sum of multiple numbers. Pupils should calculate the sum. To make the calculation easier, the sum only contains numbers 1, 2 and 3. Still, that isn’t enough for Xenia. She is only beginning to count, so she can calculate a sum only if the summands follow in non-decreasing order. For example, she can’t calculate sum 1+3+2+1 but she can calculate sums 1+1+2 and 3+3.

You’ve got the sum that was written on the board. Rearrange the summans and print the sum in such a way that Xenia can calculate the sum.

中文翻譯

Xenia 是一個剛開始學數學的國小三年級學生,她現在在學有加法的操作。

老師寫下了數個數字的加總,學生需要計算它。為了使繼續更簡單,加總只有包含了數字1,2 以及3

輸入

The first line contains a non-empty string s — the sum Xenia needs to count. String s contains no spaces. It only contains digits and characters “+”. Besides, string s is a correct sum of numbers 1, 2 and 3. String s is at most 100 characters long.

輸出

Print the new sum that Xenia can count.

印出 Xenia 可以數出的新總和

範例

輸入3+2+1
輸出1+2+3
輸入1+1+3+1+3
輸出1+1+1+3+3
輸入2
輸出2

解題思路

在這一題中,我們要先將本來的字串拆開來變成陣列

然後陣列要再從文字陣列轉為數字陣列,這樣就可以使用內建的 sort 來進行排序了

最後再將數字陣列組合回一個字串

C#解決方案

方案1

string inStr = Console.ReadLine();

string[] numStrs = inStr.Split('+');
int[] nums = new int[numStrs.Length];

for (int i = 0; i < numStrs.Length; i++)
{
    nums[i] = int.Parse(numStrs[i]);
}

Array.Sort(nums);

Console.WriteLine(String.Join("+", nums));

Java解決方案

方案1

import java.util.Scanner;
import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String[] numStrs = scanner.nextLine().split("\\+");
        int[] nums = new int[numStrs.length];
        
        for(int i=0;i<numStrs.length;i++){
            nums[i] = Integer.parseInt(numStrs[i]);
        }
        
        Arrays.sort(nums);
        
        String[] sortedStrings = new String[nums.length];
        for (int i = 0; i < nums.length; i++) {
            sortedStrings[i] = String.valueOf(nums[i]);
        }
        
        
        System.out.println(String.join("+", sortedStrings));
    }
}

Python3解決方案

方案1

inStr = input()

nums = [int(num) for num in inStr.split('+')]
nums.sort()

res_str = '+'.join(map(str, nums))

print(res_str)

結論

有點忙的一天,先寫個大概之後再補充說明 (金拍謝)

這一題當中,會用到比較多內建的函式,不管是排序還是轉型,甚至是最後將陣列組回字串的 join之類的用法 (當然也可以土法煉鋼的用 for 迴圈啦哈哈,不過那樣看起來有點遜…)

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

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

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

題目連結 : Problem – 339A – Codeforces

一些其他的文章

發佈留言

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