Power of Three
一、题目
Given an integer, write a function to determine if it is a power of three.
Example 1:
Input: 27 Output: true
Example 2:
Input: 0 Output: false
Example 3:
Input: 9 Output: true
Example 4:
Input: 45 Output: false
Follow up:
Could you do it without using any loop / recursion?
二、解决方案
1.使用loop
1 /** 2 * @param {number} n 3 * @return {boolean} 4 */ 5 var isPowerOfThree = function(n) { 6 if(n<1){ 7 return false; 8 } 9 while(n%3===0){ 10 n = n/3; 11 } 12 return n===1; 13 };
除以3一直到1为止,注意代码能简略就简略,还要考虑边界值。
Notice that we need a guard to check that n != 0
, otherwise the while loop will never finish
时间复杂度: O(log_b(n))
空间复杂度:O(1)
2.
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步