1.力扣01 位运算实现加减乘除
(1)位运算实现加法
public int add(int a,int b){
//得到原位和
int xor=a^b;
//得到进位和
int forward =(a&b)<< 1;
return forward==0? xor : add(xor,forward);
}
(2)位运算求相反数:正数取反码+1=对应负数;负数取反+1=对应正数
public int negative(int a){
return add(~a,1);
}
(3)位运算求减法:a-b=a+negative(b)
public int sub(int a,int b){
return add(a,negative(b));
}
(4)位运算求绝对值
public int abs(int a){
if(a<0){
return sub(0,a);
}
return a;
}
(5)位运算求乘法
(6)位运算求除法
public static int divide(int a, int b) {
if(a==Integer.MIN_VALUE&&b==-1){
return Integer.MAX_VALUE;
}
boolean isPositive=true;
if((a>0&&b<0)||(a<0&&b>0)){
isPositive=false;
}
long temp1=Math.abs((long)a);
long temp2=Math.abs((long)b);
int res=0;
while(temp1>=temp2){
int shift=0;
while(temp1>=temp2<<shift){
shift++;
}
temp1-=temp2<<(shift-1);
res+=1<<(shift-1);
}
return isPositive?res:-res;
}
2.力扣02 允许重复选择元素的组合
回溯+剪枝
private static Set<List<Integer>> res=new HashSet<>();
public static List<List<Integer>> getList(int[] candidates,int target){
Arrays.sort(candidates);
if(target>=candidates[0]){
for(int i=0;i<candidates.length;i++){
if(candidates[i]<=target){
List<Integer> list=new ArrayList<>();
list.add(candidates[i]);
func(list,candidates,target-candidates[i]);
}
}
}
return new ArrayList<>(res);
}
public static void func(List<Integer> list,int[] candidates,int target){
if (target==0){
list.sort((a,b)->a-b);
res.add(list);
}else if (target<candidates[0]){
return;
}
for(int i=0;i<candidates.length;i++){
if(candidates[i]<=target){
List<Integer> temp=new ArrayList<>(list);
temp.add(candidates[i]);
func(temp,candidates,target-candidates[i]);
}
}
}