LeetCode TIL 241225

두선아 DusunaΒ·2024λ…„ 12μ›” 25일

algorithm

λͺ©λ‘ 보기
7/14


Solved Problems πŸ“

241225


Key Learnings πŸ€”

Unsigned Integers & Signed Integers

AspectUnsigned IntegerSigned Integer
Negative ValuesXO
Range0 to (2^n - 1)(-2^{n-1}) to (2^{n-1} - 1)
Use of Bitsvalue1 bit for the sign, remaining bits for value

Common 32-bit Data Types in language

Language32-bit Integer TypeRange
C / C++int or uint32_t-2,147,483,648 to 2,147,483,647
Javaint-2,147,483,648 to 2,147,483,647
PythonNo explicit 32-bit type (integers are arbitrary-precision)
JavaScriptInternally uses 64-bit floating-point for numbers, but bitwise operations treat them as 32-bit signed integers.

Floating-Point in JavaScript

javaScript numbers are represented as 64-bit floating-point values by default.

However, bitwise operations (such as &, |, ^, ~, <<, >>, >>>) convert numbers to 32-bit signed integers for the operation and then convert the result back to a 64-bit floating-point number.

πŸ‘‰ This design allows a single number type to represent both integers and fractional values, simplifying the language while enabling low-level bitwise manipulation.

Common Error in JavaScript: Loss of Precision in Arithmetic

When performing arithmetic operations, the approximation of decimal values causes cumulative rounding errors.

console.log(0.1 + 0.2);  // Outputs: 0.30000000000000004

0.1 and 0.2 are both approximated in their binary form. When added together, the result is a small error due to the limitations of the floating-point representation.

πŸ‘‰ Representation cannot precisely store some decimal numbers.

so, this is the reason 0.1 + 0.2 is not 0.3 in Javascript.
Here's the corrected explanation of Precision in JavaScript Number vs Python Float:

Precision Limitation in JavaScript Number vs Python Float

Precision Limitation:
In 64-bit floating-point (IEEE 754) representation,
the precision is limited to about 15-17 decimal digits.
This can cause rounding errors during arithmetic operations.

print(0.1 + 0.2)  # Outputs: 0.30000000000000004

Python float and JavaScript Number use 64-bit floating-point format (IEEE 754)

so both python & javascript, can experience precision issues with decimal arithmetic.

If high precision is required, Python provides the decimal.Decimal module.

from decimal import Decimal

# Accurate Decimal Calculation
print(Decimal('0.1') + Decimal('0.2'))  # Outputs: 0.3

πŸ‘‰ In contrast in JavaScript to achieve similar precision, external libraries like decimal.js or big.js must be used.

to convert the Number to Binary in python.

use bin() funtion.

The bin() function in Python returns the binary representation of an integer, prefixed with 0b to indicate the value is in binary.

Why does bin() return binary code start with 0b?

The 0b prefix is used to clearly distinguish binary values from other number formats (like decimal or hexadecimal).

Filling with Zeros

To fill the space after removing the prefix? for example you can use zfill(32) to ensure a 32-bit width.

bit = bin(n)[2:].zfill(32)

How Bitwise Operations Work

Bitwise operations can directly manipulate the binary representation of numbers.

Types of Bitwise Operations

AND (&)

A B | A & B
0 0 |  0
0 1 |  0
1 0 |  0
1 1 |  1

OR (|)

A B | A | B
0 0 |  0
0 1 |  1
1 0 |  1
1 1 |  1

XOR (^)

A B | A ^ B
0 0 |  0
0 1 |  1
1 0 |  1
1 1 |  0

NOT (~)

result: two's complement of the number, equivalent to -x - 1.

  • Flips all bits of the number (1 to 0, 0 to 1)
a = 5  # Binary: 0101
result = ~a  # Binary: 1010 (Decimal: -6)
print(result)  # Output: -6

Left Shift (<<)

Equivalent to multiplying by 2^n, where n is the shift count.

  • Shifts the bits of a number to the left by a specified number of positions.
a = 5  # Binary: 0101
result = a << 1  # Binary: 1010 (Decimal: 10)
print(result)  # Output: 10

Right Shift (>>)

  • For unsigned integers, the right shift is equivalent to dividing by (2^n).
  • For signed integers, the right shift is arithmetic (sign-preserving).
    • Positive numbers behave the same as unsigned integers.
    • For negative numbers, the leftmost bits are filled with 1 to preserve the sign.
# For positive numbers:
a = 5  # Binary: 0101
result = a >> 1  # Binary: 0010 (Decimal: 2)
print(result)  # Output: 2

# For negative numbers:
a = -5  # Binary (two's complement): 11111111111111111111111111111011
result = a >> 1  # Binary: 11111111111111111111111111111101
print(result)  # Output: -3

Reversing Bits

https://leetcode.com/problems/reverse-bits/

def reverseBitsBitwise(self, n: int) -> int:
	result = 0
	for i in range(32):
		result = (result << 1) | (n & 1) # shift the result to the left & add LSB of n
		n >>= 1 # shift n to the right & remove previous LSB
	return result

To reverse the bits of a 32-bit number, bitwise operations are often used.

Least Significant Bit (LSB)

The least significant bit (LSB) is the rightmost bit of a number.

Why does n & 1 work?

using n & 1 isolates the LSB

  • n & 1 performs a bitwise AND between n and 1 (...0001).
  • If the LSB of n is 1, the result will be 1.
  • If the LSB of n is 0, the result will be 0.
profile
μ•ˆλ…•ν•˜μ„Έμš”.

0개의 λŒ“κΈ€