How to check if an integer is a power of 3?

前端 未结 23 1138
没有蜡笔的小新
没有蜡笔的小新 2020-12-02 08:15

I saw this question, and pop up this idea.

23条回答
  •  我在风中等你
    2020-12-02 08:33

    Here's a general algorithm for finding out if a number is a power of another number:

    bool IsPowerOf(int n,int b)
    {
        if (n > 1)
        {
            while (n % b == 0)
            {
                n /= b;
            }
        }
        return n == 1;
    }
    

提交回复
热议问题