Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Closed
twy30 opened this issue Nov 3, 2020 · 3 comments · Fixed by #90
Closed

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

twy30 opened this issue Nov 3, 2020 · 3 comments · Fixed by #90
Labels

Comments

@twy30
Copy link
Contributor

twy30 commented Nov 3, 2020

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 練習命名」 #69 😊

@LPenny-github
Copy link

LPenny-github commented Nov 22, 2020

再麻煩 @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
Copy link
Contributor Author

twy30 commented Nov 24, 2020

@LPenny-github

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

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

  • inputNumberAsBase2String, 或
  • inputNumberAsBinaryString

            int stepsToReduceInputNumber = binaryInputNumber.Length -1; 

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

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

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

@LPenny-github
Copy link

感謝 @twy30 大大的指導 orz

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Development

Successfully merging a pull request may close this issue.

2 participants