LeetCode:231. 2的幂283. 移动零(python3)
Posted 南岸青栀*
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode:231. 2的幂283. 移动零(python3)相关的知识,希望对你有一定的参考价值。
231. 2 的幂
法1:判断呗,直到n<2的时候
class Solution:
def isPowerOfTwo(self, n: int) -> bool:
if n == 1: return True
if n <= 0: return False
while n>=2:
print(n)
if (n%2) == 0:
n = n//2
else:
return False
return True
法2:位运算
希望自己以后看到类似的题目第一想到的就是位运算
class Solution:
def isPowerOfTwo(self, n: int) -> bool:
return n>0 and n&(n-1) == 0
if n == 1: return True
if n <= 0: return False
while n>=2:
print(n)
if (n%2) == 0:
n = n//2
else:
return False
return True
283. 移动零
法1:统计数组中0的个数,并将其删除,之后再将0添加到数组后面
class Solution:
def moveZeroes(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
# count,i = 0,0
# while i<len(nums):
# print(i)
# if nums[i] == 0:
# del nums[i]
# count += 1
# else:
# i += 1
# for i in range(count):
# nums.append(0)
法2:双指针移动法
class Solution:
def moveZeroes(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
i = 0
for j in range(len(nums)):
if nums[j] != 0:
nums[i], nums[j] = nums[j], nums[i]
i += 1
print(i,j)
return nums
以上是关于LeetCode:231. 2的幂283. 移动零(python3)的主要内容,如果未能解决你的问题,请参考以下文章