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

Overview

    • 注:草稿,题目细节内容待更新。
    • 1342. Number of Steps to Reduce a Number to Zero
    • 1356. Sort Integers by The Number of 1 Bits
    • 1374. Generate a String With Characters That Have Odd Counts


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


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’

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

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)

你可能感兴趣的:(RDpWTeHM's,LeetCode,#,数据结构与算法)