LeetCode 第 231 題:"Power of Two",相當(dāng)單純的題目。
Given an integer, write a function to determine if it is a power of two.
在之前做過 LeetCode 326 的 Power of Three, 我使用對(duì)數(shù)來處理,該實(shí)現(xiàn)代碼可以直接套用在 Power of Two 的需求上,但本文打算用 bits 來驗(yàn)證該整數(shù)是否為 2 的次方數(shù)。
Power of Three, implemented by Log()
Step 1: n 為 0 或 負(fù)數(shù),應(yīng)回傳 false
測(cè)試代碼:
[TestClass]
public class UnitTest1
{
[TestMethod]
public void n_is_less_or_equal_0_should_return_false()
{
var n = 0;
Assert.IsFalse(new Solution().IsPowerOfTwo(n));
}
}
通過測(cè)試的生產(chǎn)代碼:
public class Solution
{
public bool IsPowerOfTwo(int n)
{
if (n <= 0) return false;
throw new NotImplementedException();
}
}
重構(gòu) assertion:
refactor testing: extract method ShouldBeFalse()
Step 2: n 為 1,應(yīng)為 2 的次方
測(cè)試代碼:
n is 1, should be power of two
生產(chǎn)代碼,hard-code 通過 n = 1 回傳 true。
hard-code, when n is 1, return true
重構(gòu) assertion 的部分:
refactor testing: extract method ShouldBeTrue()
Step 3: n 為 2, 應(yīng)為 2 的次方
測(cè)試代碼:
[TestMethod]
public void n_is_2_should_return_true()
{
ShouldBeTrue(2);
}
生產(chǎn)代碼:先用 mod 2 於 0 通過此測(cè)試案例。(hard-code 通過 test case 的情況)
pass test case by mod 2
Step 4: n 為 6, 為 2 的倍數(shù),但非 2 的次方數(shù)
測(cè)試代碼:
n is 6, is not power of two
生產(chǎn)代碼:將 n 轉(zhuǎn)成 2 進(jìn)位,當(dāng) 1 的數(shù)量只有一個(gè)時(shí),代表為 2 的次方數(shù)。
convert integer to binary and should only one "1"
重構(gòu):移除 n == 1 的判斷,因?yàn)?n == 1 的商業(yè)邏輯被包含在剛剛實(shí)現(xiàn)的代碼中。
refactor: remove n == 1 condition
Step 5: 重構(gòu),rename assertion function
將原本不具語意的 ShouldBeTrue()
與 ShouldBeFalse()
rename 為 IsPowerOfTwo()
與 IsNotPowerOfTwo()
refactor testing: rename function more meaningful
通過 LeetCode 所有測(cè)試案例
Pass all test cases from LeetCode
摘要整理
- integer 轉(zhuǎn)成 2 進(jìn)位字串,可用
Convert.ToString(n, 2)
- 次方數(shù)代表只有存在單一個(gè)
"1"
- 不要因?yàn)槭菧y(cè)試程式或只是練習(xí),而忽略了語意。語意的層次在解釋說明意義,而非說明實(shí)現(xiàn)過程的細(xì)節(jié)。
ShouldBeTrue()
就是實(shí)現(xiàn)細(xì)節(jié)。IsPowerOfTwo()
才是解釋意圖。(同理,測(cè)試案例名稱也應(yīng)該修改,不該用should_be_true
而改採(cǎi)用should_be_power_of_two
GitHub Commit History: LeetCode 231. Power of Two