EngTW / English-for-Programmers

《程式英文》:用英文提昇程式可讀性
971 stars 45 forks source link

1342. Number of Steps to Reduce a Number to Zero #76

Closed twy30 closed 3 years ago

twy30 commented 3 years ago

https://leetcode.com/problems/number-of-steps-to-reduce-a-number-to-zero/

public class Solution
{
    public int NumberOfSteps(int num)
    {
        // 「輸入的數字」
        var inputNumber = num;

        if (inputNumber == 0) { return 0; }

        // 「輸出值」
        var output = -1;

        while (inputNumber > 0)
        {
            if (inputNumber % 2 != 0) { ++output; }

            ++output;

            inputNumber /= 2;
        }

        return output;
    }
}

請參考「刷 LeetCode 練習命名」 https://github.com/EngTW/English-for-Programmers/issues/69 😊

LPenny-github commented 3 years ago

再麻煩 @twy30 大大 給予命名建議 orz

我這次答題是參考 [ 從LeetCode學演算法 - 87 Bitwise Operation (6) ] https://desolve.medium.com/%E5%BE%9Eleetcode%E5%AD%B8%E6%BC%94%E7%AE%97%E6%B3%95-87-bitwise-operation-6-c464dc5975d7

感謝大大們 orz

    public int NumberOfSteps(int inputNumber)
        {
            // 答案 = inputNumber 的bit ‘1’數量 + inputNumber 的長度 - 1

            string binaryInputNumber = Convert.ToString(inputNumber, 2);

            int stepsToReduceInputNumber = binaryInputNumber.Length -1; 

            for (int i = 0; i < binaryInputNumber.Length; ++i)
            {
                if (binaryInputNumber[i] == '1')
                {
                    ++stepsToReduceInputNumber;
                }
            }
            return stepsToReduceInputNumber;
        }
twy30 commented 3 years ago

@LPenny-github

            string binaryInputNumber = Convert.ToString(inputNumber, 2);

因為這裡是從 int 轉成「二進位字串」 string, 或許可以寫成


            int stepsToReduceInputNumber = binaryInputNumber.Length -1; 

這裡雖然 stepsToReduceInputNumber 有 5 個字,但該變數名稱的語法結構 不是 堆疊字 ,所以讀起來並不困難。

如果要寫成 stepsToReduceInputNumberToZero 也不是不行 😅

或著也可以寫成 stepCount, numberOfSteps 等。

LPenny-github commented 3 years ago

感謝 @twy30 大大的指導 orz

怎麼都沒有其他人出來寫一波 XD 這樣的話……我還是會繼續寫下去的喔 XDDDD