Bit operation (below)

Novice Diary-January 21

Case number one

Represent floating point numbers in binary

The premise is to be accurate to within 32 bits, otherwise an error will be reported

Such as: 0.625

public class 二进制表示浮点数 {
    
    
    public static void main(String[] args) {
    
    
        double num = 0.625;
        StringBuilder sb = new StringBuilder("0.");
        while (num > 0){
    
    
            //乘2挪整
            double q = num * 2;
            if (q >= 1){
    
    
                sb.append("1");
                num = q - 1;
            }
            else {
    
    
                sb.append("0");
                num = q;
            }
        }
        if (sb.length() > 34){
    
    
            System.out.println("ERROR");
            return;
        }
        System.out.println(sb.toString());
    }
}

Diagram:
Insert picture description here

Effect picture:
Insert picture description here

Case 2:

K occurrences and 1 occurrence

In a number array, one number appears once, and other numbers appear k times, find the number that appears once (without auxiliary space)

1. First construct a two-dimensional array

public class 出现k次 {
    
    
    public static void main(String[] args) {
    
    
        int[] arr = {
    
    3,3,3,5,5,5,15,9,9,9,11,11,11};
        int len = arr.length;
        char [] [] kRadix = new char[len][];
        int k = 3;
        int maxLen = 0;

2. Convert each number to a character array in k base

for (int i = 0; i < len; i++) {
    
    
			//先转换为k进制的数组,再反转并转换为字符数组
            kRadix[i] = new StringBuilder(Integer.toString(arr[i], k)).reverse().toString().toCharArray();
            maxLen表示最长的k进制长度
            //如9三进制为100有三位,4为11有两位
            if (kRadix[i].length > maxLen)
                maxLen = kRadix[i].length;
        }

3. Add without carry

int[] reaArr = new int[maxLen];
        for (int i = 0; i < len; i++) {
    
    
            for (int j = 0; j < maxLen; j++) {
    
    
                //补位,不足maxLen位则用0补齐
                if (j >= kRadix[i].length) {
    
    
                    reaArr[j] += 0;
                }
                else {
    
    
                    //字符转换为整数数字
                    reaArr[j] += (kRadix[i][j] - '0');
                }
            }
        }

4. Eliminate other numbers

int res = 0;
        for (int j = 0; j < maxLen; j++) {
    
    
            //每一列的和除以k,然后乘以k的i次方,并相加
            //除了出现一次那个数的各位数的列的和,其他的都会因除以k而被消掉
            res += (reaArr[j] % k) * (int) (Math.pow(k,j));
        }
        System.out.println(res);
    }
}

Diagram:
Insert picture description here

Effect picture:
Insert picture description here

Guess you like

Origin blog.csdn.net/ghl971/article/details/112938464