Xem thảo luận
Cải thiện bài viết
Lưu bài viết
Xem thảo luận
Cải thiện bài viết
Lưu bài viết
Đọc
Examples :
Bàn luậnA simple method for this is to simply take the log of the number on base 2 and if you get an integer then number is power of 2.
Python3
Đưa ra một số nguyên dương, hãy viết một hàm để tìm nếu đó là sức mạnh của hai hoặc không.examples: & nbsp; & nbsp;
1. Một phương pháp đơn giản cho điều này là chỉ cần lấy nhật ký của số trên cơ sở 2 và nếu bạn nhận được số nguyên thì số đó là công suất của 2. & nbsp; & nbsp;
import math
import0import1import2
def Log2(x):
return (math.log10(x) /
math1math2math3math4
math6math7math8math9
def0def1
math6math7def5math9
math1math2def9math4
math6math7math8math9
def0def1
math6math7def5math9
def import4O(log2n)
return import7import8import8 math0O(1)
Độ phức tạp về thời gian: O (log2N)Another solution is to keep dividing the number by two, i.e, do n = n/2 iteratively. In any iteration, if n%2 becomes
non-zero and n is not 1 then n is not a power of 2. If n becomes 1 then it is a power of 2.
Python3
def Log2(x):
return (math.log10(x) /
def import4
return import7import8import8 math0
Độ phức tạp về thời gian: O (log2N)
Không gian phụ trợ: O (1)
2. Một giải pháp khác là tiếp tục chia số cho hai, tức là làm n = n/2 lặp đi lặp lại. Trong bất kỳ lần lặp nào, nếu n%2 trở thành khác không và n không phải là 1 thì n không phải là sức mạnh của 2. Nếu n trở thành 1 thì đó là sức mạnh của 2. & nbsp;
math1 7import8import8 return0return1
math1math2math3math4
math6math7import00import01
def0def1
math6math7import07import01
math1math2def9math4
math6math7import00import01
def0def1
math6math7import07import01
return2return return4All power of two numbers have only one bit set. So count the no. of set bits and if you get 1 then number is
a power of 2. Please see Count set bits in an integer for counting set bits.
4. If we subtract a power of 2 numbers by 1 then all unset bits after the only set bit become set; and the set bit become unset.
For example for 4 ( 100) and 16(10000), we get following after subtracting 1
3 –> 011
15 –> 01111
So, if a number n is a power of 2 then bitwise & of
n and n-1 will be zero. We can say n is a power of 2 or not based on value of n&(n-1). The expression n&(n-1) will not work when n is 0. To handle this case also, our expression will become n& (!n&(n-1)) (thanks to //www.geeksforgeeks.org/program-to-find-whether-a-no-is-power-of-two/Mohammad for adding this case).
Below is the implementation of this
method.
Python3
return6 return7import8 return9return1
math1 7__74
math1math2math3math4
math6math7import00import01
def0def1
math6math7import07import01
math1math2def9math4
math6math7import00import01
def0def1
/0return return4
/4import8 /4// import1