Kata Practice C# - Opposites Attract

Kata Practice C# - Opposites Attract

這個系列會把自己練習過的 Kata 題目記錄下來,希望除了記錄的性質以外也能夠觀察自己撰寫程式邏輯的進化過程。如果有幸看到這邊的話也可以參考一下,再到 Codewars 的網站註冊一個帳號試著玩看看,自己蠻喜歡整個網站的得分和排行榜設定,會讓人越寫越有成就感喔!

題目

Timmy & Sarah think they are in love, but around where they live, they will only know once they pick a flower each. If one of the flowers has an even number of petals and the other has an odd number of petals it means they are in love.

Write a function that will take the number of petals of each flower and return true if they are in love and false if they aren’t.

1
2
3
4
5
6
7
8
9
using System;

public class LoveDetector
{
public static bool lovefunc(int flower1, int flower2)
{
//Moment of truth...
}
}

自己的解法

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

public class LoveDetector
{
public static bool lovefunc(int flower1, int flower2)
{
if( flower1 % 2 == 0 && flower2 % 2 == 0 ){
return false;
}
else if ( flower1 % 2 != 0 && flower2 % 2 != 0){
return false;
}
return true;
}
}

解題脈絡

一開始就是照著題目的 Description 來寫,所以其實程式碼很直觀,但換個說法就是爛到不行哈哈!
不過我覺得對於自己目前的程度來說就是盡量地用自己現有的思維去寫,然後再透過大家的 Solution 來學習別人寫程式的邏輯。
可以備註的地方應該是在解題時我就有知道這樣的解法不是最佳解,這樣就是把所有的條件都各別列出來而已。

其他人的解法

1
2
3
4
5
6
7
8
9
using System;

public class LoveDetector
{
public static bool lovefunc(int flower1, int flower2)
{
return (flower1 + flower2) % 2 == 1;
}
}

選擇這個解法的原因

這邊的話會盡量選擇自己看得懂而且能夠理解的寫法來做紀錄,其實同樣的練習可能還有你認為更好的做法,那這部分你可以透過自己解題 Submit 後再去參考其他人的。
會選擇這個解法的原因是 flower1 + flower2 如果被 2 取餘數是 1 的話就代表這兩個參數有一個不是雙數了,因此兩個雙數相加後取餘數就會等於 0 並符合題目要求的返回 False 的值。

觀念釐清

後來發現是自己沒有搞清楚 % 這個算術運算子的功能其實是取餘數,所以才繞了一大圈把所有的條件都寫出來,雖然有點丟臉但不過現在也因此加深印象了 XD

那我們下次見ʘ‿ʘ

評論