楼主:
dont 2024-07-21 12:05:39第一题
Number of Bit Changes to Make Two Integers Equal
## 思路
扫32bit,
如果k的bit为0,n的bit为1 回传-1
如果k的bit为1,n的bit为0 change+1
## Code
```python
class Solution:
def minChanges(self, n: int, k: int) -> int:
ans = 0
for i in range(32):
if n & 1 and k & 1 == 0:
ans += 1
if n & 1 == 0 and k & 1:
return -1
n >>= 1
k >>= 1
return ans
```
第二题
Vowels Game in a String
## 思路
计算vowels数量,
奇数个 - Alice直接获胜
偶数个 - 删掉奇数个vowels会剩下三种Case: bab / ba / a, 也都会是Alice获胜
所以只有零个的时候会是False
## Code
```python
class Solution:
def doesAliceWin(self, s: str) -> bool:
vowels = {'a', 'e', 'i', 'o', 'u'}
count = 0
for ch in s:
if ch in vowels:
count += 1
if count == 0:
return False
return True
```
第三题
Maximum Number of Operations to Move Ones to the End
## 思路
由左往右扫, 纪录1的个数ones
每次遇到0的时候就移动ones个1 (重复0时略过)
## Code
```python
class Solution:
def maxOperations(self, s: str) -> int:
n = len(s)
ans = ones = 0
i = 0
for i in range(n):
if i and s[i] == s[i-1] == '0':
continue
if s[i] == '0':
ans += ones
else:
ones += 1
return ans
```
第四题
Minimum Operations to Make Array Equal to Target
## 思路
如果 diff[1:3] > 0 而 diff[3] <= 0 的时候
只会对nums[1:3] 做Increment, 对nums[3:??] 做Decrement
在nums[1:3]范围内就是加上diff差值
## Code
```python
class Solution:
def minimumOperations(self, nums: List[int], target: List[int]) -> int:
n = len(nums)
diff = [n-t for n, t in zip(nums, target)]
ans = abs(diff[0])
for i in range(1, n):
if diff[i] * diff[i-1] <= 0:
ans += abs(diff[i])
else:
ans += max(abs(diff[i]) - abs(diff[i-1]), 0)
return ans
```