关于二进制的算法

17 篇文章 0 订阅
17 篇文章 0 订阅

二进制中1的个数

输入一个整数 n ,输出该数32位二进制表示中1的个数。其中负数用补码表示。
n&(n-1):n 的二进制位中的最低位的 1 变为 0之后的结果

public int NumberOf1(int n) {
        int count=0;
        while(n!=0){
            count++;
            n=n&(n-1);
        }
        return count;
    }
    

如果一个整数不为0,那么这个整数至少有一位是1。如果我们把这个整数减1,那么原来处在整数最右边的1就会变为0,原来在1后面的所有的0都会变成1(如果最右边的1后面还有0的话)。其余所有位将不会受到影响。

数值的整数次方

给定一个double类型的浮点数base和int类型的整数exponent。求base的exponent次方。

保证base和exponent不同时为0。不得使用库函数,同时不需要考虑大数问题,也不用考虑小数点后面0的位数。

public class Solution {
    public double Power(double base, int n) {
    	double res = 1,curr = base;
    	int exponent;
    	if(n>0){
    		exponent = n;
    	}else if(n<0){
    		if(base==0)
    			throw new RuntimeException("分母不能为0");  
    		exponent = -n;
    	}else{// n==0
    		return 1;// 0的0次方
    	}
    	while(exponent!=0){
			if((exponent&1)==1)
				res*=curr;
			curr*=curr;// 翻倍
			exponent>>=1;// 右移一位
		}
		return n>=0?res:(1/res);        
  	}
}

参考快速幂:https://blog.csdn.net/weixin_43553694/article/details/106140302

集合的所有子集

位运算:

public class Solution {
    public ArrayList<ArrayList<Integer>> subsets(int[] S) {
        ArrayList<ArrayList<Integer>> res = new ArrayList<>();
        if(S.length==0) return res;
        Arrays.sort(S);
        int end=1<<S.length;
        for(int i=0;i<end;i++){
            // j位置要么是true选中,要么是false不选
            // 这里其实就是想判断,将i转成二进制之后,从右往左数第j+1位是不是1
            ArrayList array = new ArrayList<>(i);
            for(int j=0;j<S.length;j++){
                if((1<<j & i) !=0){
                array.add(S[j]);
                }
            }
            res.add(array);
        }
        return res;
    }
}

比较好理解

	public static ArrayList<ArrayList<Integer>> getSubset(ArrayList<Integer> L) {
		if (L.size() > 0) {
			ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
			for (int i = 0; i < Math.pow(2, L.size()); i++) {// 集合子集个数=2的该集合长度的乘方
				ArrayList<Integer> subSet = new ArrayList<Integer>();
				int index = i;// 索引从0一直到2的集合长度的乘方-1
				for (int j = 0; j < L.size(); j++) {
					// 通过逐一位移,判断索引那一位是1,如果是,再添加此项
					if ((index & 1) == 1) {// 位与运算,判断最后一位是否为1
						subSet.add(L.get(j));
					}
					index >>= 1;// 索引右移一位
				}
				result.add(subSet); // 把子集存储起来
			}
			return result;
		} else {
			return null;
		}
	} 
}

回溯

import java.util.*;

public class Solution {
    ArrayList<arraylist<integer>&gt;result=new ArrayList&lt;&gt;();
    ArrayList<integer>path=new ArrayList<integer>();
    void backtracing(int[] S,int len,int index){
        result.add(new ArrayList&lt;&gt;(path));//不能跟C++一样直接result.add(path).......
        for(int i=index;i<len;++i){ path.add(s[i]); backtracing(s,len,i+1); path.remove(path.size()-1); } public arraylist<arraylist<integer>&gt; subsets(int[] S) {
        Arrays.sort(S);
        backtracing(S,S.length,0);
        return result;
    }
}

迭代

import java.util.*;

public class Solution {
    public ArrayList<ArrayList<Integer>> subsets(int[] S) {
        int n=S.length;
        ArrayList<ArrayList<Integer>>ans=new ArrayList<>();
        ans.add(new ArrayList<Integer>());
        for(int i=0;i<n;++i){
            int size=ans.size();
            for(int j=0;j<size;++j){
                ArrayList<Integer>path=new ArrayList<Integer>();
                path.addAll(ans.get(j));
                path.add(S[i]);
                ans.add(path);
            }
        }
        return ans;
    }
}

懂二进制

世界上有10种人,一种懂二进制,一种不懂。那么你知道两个int32整数m和n的二进制表达,有多少个位(bit)不同么?

public int countBitDiff(int m, int n) {
        int res = 0;
        int val = m ^ n;
        while(val != 0){
            res += val & 1;
            val = val >> 1;
        }
        return res;
    }

整数除法

给定两个整数 a 和 b ,求它们的除法的商 a/b ,要求不得使用乘号 ‘*’、除号 ‘/’ 以及求余符号 ‘%’ 。

public int divide(int a, int b) {
    // 32 位最大值:2^31 - 1 = 2147483647
    // 32 位最小值:-2^31 = -2147483648
    // -2147483648 / (-1) = 2147483648 > 2147483647 越界了
    if (a == Integer.MIN_VALUE && b == -1)
        return Integer.MAX_VALUE;
    int sign = (a > 0) ^ (b > 0) ? -1 : 1;
    // 环境只支持存储 32 位整数
    if (a > 0) a = -a;
    if (b > 0) b = -b;
    int res = 0;
    while (a <= b) {
        a -= b;
        res++;
    }
    // bug 修复:因为不能使用乘号,所以将乘号换成三目运算符
    return sign == 1 ? res : -res;}
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值