20210909LeetCode

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]);
            }
        }


    }

                
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值