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

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

I saw this question, and pop up this idea.

23条回答
  •  一整个雨季
    2020-12-02 08:32

    I find myself slightly thinking that if by 'integer' you mean 'signed 32-bit integer', then (pseudocode)

    return (n == 1) 
        or (n == 3)
        or (n == 9)
        ... 
        or (n == 1162261467) 
    

    has a certain beautiful simplicity to it (the last number is 3^19, so there aren't an absurd number of cases). Even for an unsigned 64-bit integer there still be only 41 cases (thanks @Alexandru for pointing out my brain-slip). And of course would be impossible for arbitrary-precision arithmetic...

提交回复
热议问题