본문 바로가기

bitwise3

[LeetCode] Number Complement 파이썬 (format, bitwise) format() 함수를 사용해서 진법을 출력할때 앞의 str를 제거하고 출력할 수 있다. Format Specification Mini-Language 이런식으로 출력된다. print(format(num, 'b')) print(bin(num)) class Solution: def findComplement(self, num: int) -> int: com_bi = [str(abs(int(x)-1)) for x in str(format(num, 'b'))] return com_bi abs(int(x) - 1) 을 해줌으로써 1 -> 0 , 0 -> 1로 swap 해준다. 2021. 4. 19.
[LeetCode] Hamming Distance 파이썬 (bitwise) class Solution(object): def hammingDistance(self, x, y): """ :type x: int :type y: int :rtype: int """ distance = 0 z = x ^ y while z: distance += 1 z &= z - 1 return distance def hammingDistance2(self, x, y): """ :type x: int :type y: int :rtype: int """ return bin(x ^ y).count('1') 2번째 솔루션 비트 XOR 연산으로 position이 서로 다른지 확인한다. x = 1, y = 4일 경우 001 XOR 100 = 101 이 str에서 count메서드를 사용해서 1의 횟수를 retur.. 2021. 4. 19.
[LeetCode] Longest Palindrome 파이썬 (bitwise &, Counter) from collections import Counter class Solution(object): def longestPalindrome(self, s): """ :type s: str :rtype: int """ odds = 0 for k, v in Counter(s).items(): odds += v & 1 return len(s) - odds + int(odds > 0) lambda, map을 사용해서 홀 수 인 s 구하기 def longestPalindrome2(self, s): """ :type s: str :rtype: int """ odd = sum(map(lambda x: x & 1, Counter(s).values())) return len(s) - odd + int(odd > 0) 홀.. 2021. 4. 16.