zoukankan      html  css  js  c++  java
  • lintcode二进制和位运算

    由于python的整形位数和平台有关,而且有自动提升的机制,所以不适合做这类题目。

    这篇随笔中大部分题目都是用java实现的,感觉自己java常用的方法还是不熟悉。

    -------------------------------------------------------------------

    365.二进制求和

    给定两个二进制字符串,返回他们的和(用二进制表示)。

    输入是字符串的话,py还是有优势的。

    class Solution:
        # @param {string} a a number
        # @param {string} b a number
        # @return {string} the result
        def addBinary(self, a, b):
            # Write your code here
            result = ['0'] * (max(len(a), len(b)) + 1)
            s = c = False
            i = 1
            while i < len(a) + 1 and i < len(b) + 1:
                s = (not c and (a[-i] != b[-i])) or (c and (a[-i] == b[-i]))
                if s:
                    result[-i] = '1'
                c = (a[-i] == '1' and b[-i] == '1') or (c and (a[-i] != b[-i]))
                i += 1
            while i < len(a) + 1:
                s = (not c and a[-i] == '1') or (c and a[-i] == '0')
                if s:
                    result[-i] = '1'
                c = a[-i] == '1' and c
                i += 1
            while i < len(b) + 1:
                s = (not c and b[-i] == '1') or (c and b[-i] == '0')
                if s:
                    result[-i] = '1'
                c = b[-i] == '1' and c
                i += 1
            if c:
                result[-i] = '1'
                
            return ''.join(result[1:] if result and result[0] == '0' else result)
    

    -------------------------------------------------------------------

    408.二进制中有多少个1

    计算在一个 32 位的整数的二进制表式中有多少个 1.

    使用无符号右移>>>。

    public class Solution {
        /**
         * @param num: an integer
         * @return: an integer, the number of ones in num
         */
        public int countOnes(int num) {
            // write your code here
            int result = 0;
            while(num != 0){
                if((num & 1) > 0){
                    result++;
                }
                num = num >>> 1;
            }
            return result;
        }
    };
    

    -------------------------------------------------------------------

    411.格雷编码

    给定一个非负整数 n ,表示该代码中所有二进制的总数,请找出其格雷编码顺序。

    循环版本实在是有点绕,说不定递归的简单点。

    class Solution:
        # @param {int} n a number
        # @return {int[]} Gray code
        def grayCode(self, n):
            # Write your code here
            if n == 0:
                return [0]
            result = []
            for i in range(2 ** n):
                bin_i = ['0'] * n
                temp = i
                for j in xrange(n):
                    if temp < 2 ** (n - j) and temp >= 2 ** (n - j - 1):
                        bin_i[j] = '1'
                    if temp >= 2 ** (n - j) and temp < 2 ** (n - j) + 2 ** (n - j - 1):
                        bin_i[j] = '1'
                    if temp >= 2 ** (n - j):
                        temp -= 2 ** (n - j)
                result.append(''.join(bin_i))
            return [int(r, 2) for r in result]
    

    -------------------------------------------------------------------

    1.A + B 问题

    给出两个整数a和b, 求他们的和, 但不能使用 + 等数学运算符。

    思路和二进制加法一样,专门实现了一个函数用来检测数字的某一位是1还是0.

    class Solution {
        /*
         * param a: The first integer
         * param b: The second integer
         * return: The sum of a and b
         */
        public int aplusb(int a, int b) {
            // write your code here, try to do it without arithmetic operators.
            int res = 0;
            boolean s = false;
            boolean c = false;
            for(int i = 0; i < 32; i++){
                s = (testBit(a, i) == testBit(b, i)) ^ (!c);
                if(s){
                    res += 1 << i;
                }
                c = ((testBit(a, i) == 1 && testBit(b, i) == 1) || 
                        (c && (testBit(a, i) != testBit(b, i))));
            }
            return res;
        }
        
        public int testBit(int a, int index){
            int shift = 1 << index;
            return ((a & shift) != 0) ? 1 : 0; 
        }
    };
    

    -------------------------------------------------------------------

    142.O(1)时间检测2的幂次

    用 O(1) 时间检测整数 n 是否是 2 的幂次。

    class Solution:
        """
        @param n: An integer
        @return: True or false
        """
        def checkPowerOf2(self, n):
            # write your code here
            if n <= 0:
                return False
            return bin(n).count('1') == 1
    

    -------------------------------------------------------------------

    179.更新二进制位

    给出两个32位的整数N和M,以及两个二进制位的位置i和j。写一个方法来使得N中的第i到j位等于M(M会是N中从第i为开始到第j位的子串)

    先将n中i~j范围置0,然后将m左移位i,之后n+=m。

    class Solution {
        /**
         *@param n, m: Two integer
         *@param i, j: Two bit positions
         *return: An integer
         */
        public int updateBits(int n, int m, int i, int j) {
            // write your code here
            int low = 0;
            for(int x = 0; x < i; x++){
                low = (low << 1) + 1;
            }
            int high = 0;
            if(j < 31){
                high = -1 << j + 1;
            }
            else{
                high = 0;
            }
            n = n & (high + low);
            n += m << i;
            return n;
        }
    }
    

    -------------------------------------------------------------------

    180.二进制表示

    给定一个数将其转换为二进制(均用字符串表示),如果这个数的小数部分不能在 32 个字符之内来精确地表示,则返回 "ERROR"

    小数点前的用Integer.toBinaryString直接转,后面使用基数连乘法,最后一起输出。

    public class Solution {
        /**
         *@param n: Given a decimal number that is passed in as a string
         *@return: A string
         */
        public String binaryRepresentation(String n) {
            // write your code here
            if(n == null || n == "" || n.charAt(0) == '-'){
                return "ERROR";
            } 
            try{
                String result = "";
                result = Integer.toBinaryString(
                    Integer.parseInt(n.split("\.")[0])
                    ) + ".";
                double target = Double.parseDouble(
                    "0." + n.split("\.")[1]
                    );
                String result1 = "";
                while(result1.length() <= 32 && target - 0 > 1e-10){
                    target = target * 2;
                    if(target >= 1){
                        result1 += "1";
                        target -= 1;
                    }
                    else{
                        result1 += "0";
                    }
                }
                result += result1;
                if(result1.length() <= 32){
                    return (result.split("\.").length > 1)? result : result.split("\.")[0]; 
                }
                return "ERROR";
            }
            catch(Exception e){
                return "ERROR";
            }
        }
    }
    

    -------------------------------------------------------------------

    181.将整数A转换为B

    如果要将整数A转换为B,需要改变多少个bit位?

    class Solution:
        """
        @param a, b: Two integer
        return: An integer
        """
        def bitSwapRequired(self, a, b):
            # write your code here
            return bin(a ^ b).count('1')
    

      

  • 相关阅读:
    algorithm
    jstl
    jsp
    cookie
    变量和方法调用过程中会出现的参数传递
    http请求
    weblogic 的安全域问题
    web service
    行业充电
    客户端生成web service
  • 原文地址:https://www.cnblogs.com/zcy-backend/p/6748283.html
Copyright © 2011-2022 走看看