[LeetCode] Power of Three | Power of Two

简介: Given an integer, write a function to determine if it is a power of three.Follow up: Could you do it without using any loop / recursion?解题思路log运算。实现代码//Runtime: 18 mspublic cl

Given an integer, write a function to determine if it is a power of three.

Follow up:
Could you do it without using any loop / recursion?

解题思路

log运算。

实现代码

//Runtime: 18 ms
public class Solution {
    public boolean isPowerOfThree(int n) {
        double res = Math.log(n) / Math.log(3);
        return Math.abs(res - Math.round(res)) < 1e-10;
    }
}

Given an integer, write a function to determine if it is a power of two.

解题思路

2的n次方,必然大于0;而且二进制位中只有一个1。

实现代码

public class Solution {
    public boolean isPowerOfTwo(int n) {
        return n > 0 && (n & n - 1) == 0;
    }
}
目录
相关文章
|
存储 缓存 算法
LeetCode刷题---Two Sum(一)
LeetCode刷题---Two Sum(一)
|
存储 算法 安全
LeetCode - #2 Add Two Numbers
我们社区从本期开始会将顾毅(Netflix 增长黑客,《iOS 面试之道》作者,ACE 职业健身教练。)的 Swift 算法题题解整理为文字版以方便大家学习与阅读。 不积跬步,无以至千里;不积小流,无以成江海,Swift社区 伴你前行。
270 0
LeetCode - #2 Add Two Numbers
|
存储 算法 安全
LeetCode - #1 Two Sum
我们社区从本期开始会将顾毅(Netflix 增长黑客,《iOS 面试之道》作者,ACE 职业健身教练。)的 Swift 算法题题解整理为文字版以方便大家学习与阅读。 不积跬步,无以至千里;不积小流,无以成江海,Swift社区 伴你前行。
142 0
LeetCode - #1 Two Sum
Leetcode 4. Median of Two Sorted Arrays
题目描述很简单,就是找到两个有序数组合并后的中位数,要求时间复杂度O(log (m+n))。 如果不要去时间复杂度,很容易就想到了归并排序,归并排序的时间复杂度是O(m+n),空间复杂度也是O(m+n),不满足题目要求,其实我开始也不知道怎么做,后来看了别人的博客才知道有个二分法求两个有序数组中第k大数的方法。
200 0
|
存储 C++ Python
LeetCode刷题---Add Two Numbers(一)
LeetCode刷题---Add Two Numbers(一)
LeetCode 350. Intersection of Two Arrays II
给定两个数组,编写一个函数来计算它们的交集。
269 0
LeetCode 350. Intersection of Two Arrays II
|
Python
LeetCode 349. Intersection of Two Arrays
给定两个数组,编写一个函数来计算它们的交集。
267 0
LeetCode 349. Intersection of Two Arrays
LeetCode 342. Power of Four
给定一个整数 (32 位有符号整数),请编写一个函数来判断它是否是 4 的幂次方。
215 0
LeetCode 342. Power of Four
LeetCode 160. Intersection of Two Linked Lists
编写一个程序,找到两个单链表相交的起始节点。
246 0
LeetCode 160. Intersection of Two Linked Lists
Leetcode-Easy21. Merge Two Sorted Lists
Leetcode-Easy21. Merge Two Sorted Lists
223 0
Leetcode-Easy21. Merge Two Sorted Lists