一、Sum of Two Integers
不使用 + - 号计算两个数的和
1.计算进位,carry=a&b
2.异或(半加法,不包含进位的加法)a=a^b
3.进位应该加在前一位,carry左移1位,b赋值为carry,直到b=0
class Solution {
public int getSum(int a, int b) {
if (a==0) return b;
if (b==0) return a;
while(b!=0){
int carry=a&b;
a=a^b;
b=carry << 1;
}
return a;
}
}
二、Move Zeroes
给定一个数组,把所有0移动到数组最后,保持非零元素的相对位置
class Solution(object):
def moveZeroes(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
zero=0 #记录元素0的位置
for i in xrange(len(nums)):
if nums[i]!=0:
nums[zero],nums[i]=nums[i],nums[zero]
zero+=1
#简洁的sort方法
nums.sort(key=labmda x:1 if x==0 else 0)
三、 Product of Array Except Self
给定一个包含n个数字的数组nums,返回一个数组res,res[i]元素是nums数组中除了nums[i]以外的所有数字的乘积,(不使用除法)
[1,2,3,4]=>[2x3x4,1x3x4,1x2x4,1x2x3]=>[24,12,8,6]
思路:
初始化res=[1,1…1,1]
遍历两次,
第一次,从左往右,res[i]乘以第i个元素左边所有元素的乘积
第二次,从右往左,res[i]乘以第i个元素右边所有元素的乘积
class Solution(object):
def productExceptSelf(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
l=len(nums)
res=[1]*l
p=1
for i in range(l):
res[i]*=p
p*=nums[i]
p=1
for i in range(-1,-l-1,-1):
res[i]*=p
p*=nums[i]
return res