avatar
Siz Long

My name is Siz. I am a computer science graduate student specializing in backend development with Golang and Python, seeking opportunities in innovative tech projects. My personal website is me.longsizhuo.com .Connect with me on LinkedIn: https://www.linkedin.com/in/longsizhuo/.

  • Resume
  • Archives
  • Categories
  • Photos
  • Music



{{ date }}

{{ time }}

avatar
Siz Long

My name is Siz. I am a computer science graduate student specializing in backend development with Golang and Python, seeking opportunities in innovative tech projects. My personal website is me.longsizhuo.com .Connect with me on LinkedIn: https://www.linkedin.com/in/longsizhuo/.

  • 主页
  • Resume
  • Archives
  • Categories
  • Photos
  • Music

2997. Make an array or harmony K The minimum number of operations

  2024-01-01        
字数统计: 251字   |   阅读时长: 1min

topic:

screenshot2024-01-10 afternoon4.17.31.png

Thought:

  1. firstBit operation有三个特性:
    1. Any number and0Different or operational,The result is still the original number,Right now a XOR 0 = a。
    2. Any number and自身Different or operational,turn out0,Right now a XOR a = 0。
    3. Different or operations meet the law of exchange and binding。
1
2
3
4
5
a = 0b1001
b = 0b0110
bin(a ^ b)

'0b1111'

first,We need to calculate the array nums All elements of all elements,Be remembered xor_sum。Our goal is to make some positions to make xor_sum equal k。

then,We can consider xor_sum XOR k the result of。Due to the characteristics of different or computing,The difference in any position will cause the bit in the result to be1。this means,We need to change xor_sum and k All different places in binary representation。

if xor_sum = 1010,k = 0011,So xor_sum XOR k = 1001。We need to change第一位and第四位来让 xor_sum become k。

That is numsHeterogeneityand kValue, in1The number is the number that needs to be converted。can watch0x3fSolution

Code:

I am
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution:
def minOperations(self, nums: List[int], k: int) -> int:
xor_sum = 0
for num in nums:
xor_sum ^= num

xor_diff = xor_sum ^ k
operations = 0

# Calculate the digits that need to be changed
while xor_diff:
operations += xor_diff & 1
xor_diff >>= 1

return operations
0x3f
1
2
3
4
5
6
func minOperations(nums []int, k int) int {
for _, x := range nums {
k ^= x
}
return bits.OnesCount(uint(k))
}
  • Python
  • solved
  • Bit operation

扫一扫,分享到微信

微信分享二维码
271. Code and decoding of string - Python Add the transposition symbol solution method Dual complexityO(n)
2998. make X and Y Equal number of operations
目录
  1. 1. topic:
  2. 2. Thought:
  3. 3. Code:

153 篇 | 133k
次 | 人
这里自动载入天数这里自动载入时分秒
2022-2025 loong loong | 新南威尔士龙龙号