【Leetcode】二进制解法题目整理(包括与、或、XOR逻辑运算) - 更新中


注:草稿,题目细节内容待更新。


1342. Number of Steps to Reduce a Number to Zero

2020/07/22

Given a non-negative integer num, return the number of steps to reduce it to zero. If the current number is even, you have to divide it by 2, otherwise, you have to subtract 1 from it.

@sodinfeliz

Python 3 by using collections (explained)

algorithm consists of two process:

  1. if the last digit is 1, then turn the digit into 0 eg. ‘10001’ -> ‘10000’
  2. else all bits shifted to the left eg. ‘10000’ -> ‘1000’

img

class Solution:
 def numberOfSteps (self, num: int) -> int:
     bin_num = bin(num)[2:]
     return collections.Counter(bin_num)['1'] + len(bin_num) - 1

1356. Sort Integers by The Number of 1 Bits

2020/07/22

class Solution:
    def sortByBits(self, arr: List[int]) -> List[int]:
        return sorted(arr, key=lambda v: (sum([int(_) for _ in bin(v)[2:]]), v))

不用 bin(v)[2:] + sum(_) 的一行(使用 count)

class Solution:
 def sortByBits(self, arr: List[int]) -> List[int]:
     return sorted(arr, key = lambda x: (bin(x).count("1"), x))

1374. Generate a String With Characters That Have Odd Counts

2020/07/26

Solution:

class Solution:
    def generateTheString(self, n: int) -> str:
        return 'b' + 'ab'[n & 1] * (n - 1)

no binary:

def solution(n):
    return 'a' * (n if n % 2 != 0 else n-1) + 'b' * (1 if n % 2 == 0 else 0)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值