181.Flip Bits-将整数A转换为B(容易题)

本文探讨了如何计算将一个整数A转换为另一个整数B时需要改变的bit位数量。通过异或运算结合无符号右移运算符实现高效解决方案。

将整数A转换为B

  1. 题目

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

  2. 样例

    如把31转换为14,需要改变2个bit位。
    (31)10=(11111)2
    (14)10=(01110)2

  3. 挑战

    你能想出几种方法?

  4. 题解

    本题优先考虑的就是二进制运算,由题意自然想到的就是异或运算。以样例为例:11111^01110=10001,则10001中为1的bit位的个数就是答案。
    但是这里有个坑要注意,就是处理异或结果为负数的情况。因为负数移位运算会保持原符号,在本题右移位运算中会始终在高位补1,会造成死循环。
    解决的方法有两个,一是将负数转换成除最高位不同其余位全部相同的正数再进行处理(结果需要+1)

        num=Integer.MAX_VALUE + num + 1;

二是使用无符号右移运算符>>>。

class Solution {
    /**
     *@param a, b: Two integer
     *return: An integer
     */
    public static int bitSwapRequired(int a, int b) {
        int count = 0;
        for (int num = a^b;num != 0;num >>>= 1)
        {
            count += num&1;
        }
        return count;
    }
};

Last Update 2016.9.9

import math import numpy as np import matplotlib.pyplot as plt import torch import torch.nn as nn import torch.optim as optim import tikzplotlib def my_bisection(f, a, b, P, tol): # approximates a root, R, of f bounded # by a and b to within tolerance # | f(m) | < tol with m the midpoint # between a and b Recursive implementation # check if a and b bound a root if (f(a) > P and f(b) > P) or (f(a) < P and f(b) < P): raise Exception( "The scalars a and b do not bound P") # get midpoint m = (a + b)/2 if np.abs(f(m)-P) < tol: # stopping condition, report m as root return m elif f(m) > P and f(m) < f(a): # case where m is an improvement on a. # Make recursive call with a = m return my_bisection(f, m, b, P, tol) elif f(m) < P and f(m) > f(b): # case where m is an improvement on b. # Make recursive call with b = m return my_bisection(f, a, m, P, tol) def AWGN_channel(x, sigma2): noise = np.sqrt(sigma2) * np.random.randn(x.size) return x + noise’ def AWGNdemapper(y, const, varN): apps = np.exp(-np.abs(np.transpose([y])-const)**2/(2*varN)) return apps / np.transpose([np.sum(apps, 1)]) def sampler(prob, n): samples = np.empty(0) for idx, p in enumerate(prob): occurrences = np.round(n * p) samples = np.concatenate((samples, np.ones(occurrences.astype(int)) * idx)) indexes = np.random.permutation(samples.shape[0]) return samples[indexes] def xesmd(apps, idx): ‘’’ Estimates symbolwise equivocation from reference symbols indices and a posteriori probabilities. ‘’’ eq = -np.log(np.take_along_axis(apps, idx[:, None], axis=1) / np.transpose([np.sum(apps, 1)])) eq[eq==np.inf] = 1000 return np.mean(eq) n = 100_000 SNR_dBs = np.arange(5,25) 16 QAM M = 4 alphabet = np.arange(-3,4,2) alphabet = alphabet / np.sqrt(np.mean(alphabet**2)) indices = np.random.choice(np.arange(M), n) symbols = alphabet[indices] mi_16 = [] for snrdB in SNR_dBs: sigma2 = 1/(10**(snrdB/10)) sigma2 = sigma2 y = AWGN_channel(symbols, sigma2) apps = AWGNdemapper(y, alphabet, sigma2) xe = xesmd(apps, indices) mi_16.append(2*(2 - xe / np.log(2))) 64 QAM M = 8 alphabet = np.arange(-7,8,2) alphabet = alphabet / np.sqrt(np.mean(alphabet**2)) indices = np.random.choice(np.arange(M), n) symbols = alphabet[indices] print('Power: ',np.mean(np.square(symbols))) mi_64 = [] for snrdB in SNR_dBs: sigma2 = 1/(10**(snrdB/10)) sigma2 = sigma2 y = AWGN_channel(symbols, sigma2) apps = AWGNdemapper(y, alphabet, sigma2) xe = xesmd(apps, indices) mi_64.append(2*(3 - (xe) / np.log(2))) def power_for_shaping(shaping): alphabet = np.arange(-7,8,2) # alphabet = alphabet / np.sqrt(np.mean(alphabet**2)) scaling = (alphabet[1]-alphabet[0])/2 denominator = np.sum(np.exp(-shaping*np.square(alphabet))) probs = 1/denominator * np.exp(-shaping*np.square(alphabet)) power = np.sum(np.square(np.arange(-7,8,2)*(scaling))*probs) return power power = [] for i in np.arange(0,1,0.1): power.append(power_for_shaping(i)) plt.plot(np.arange(0,1,0.1), power) M = 8 shaping = 2.5 alphabet = np.arange(-7,8,2) alphabet = alphabet / np.sqrt(np.mean(alphabet**2)) scaling = (alphabet[1]-alphabet[0])/2 scaling = 0.21821789023599236 print('Scaling: ', scaling) denominator = np.sum(np.exp(-shapingnp.square(alphabet))) probs = 1/denominator * np.exp(-shapingnp.square(alphabet)) power = np.sum(np.square(np.arange(-7,8,2)*(scaling))*probs) print('Power: ', power) indices = sampler(probs, n).astype(int) norm_factor = np.sqrt(np.sum(np.square(alphabet) * probs)) alphabet = alphabet / norm_factor symbols = alphabet[indices] scaling = (alphabet[1]-alphabet[0])/2 print('Scaling: ', scaling) H = np.sum(-np.log2(probs)*probs) print('Entropy: ',H) power = np.mean(symbols2) print('Power: ', power) plt.rcParams[‘figure.figsize’] = [4, 4] plt.hist(symbols, bins=100) plt.show() mi_mb_64 = [] for snrdB in SNR_dBs: sigma2 = 1/(10(snrdB/10)) sigma2 = sigma2 y = AWGN_channel(symbols, sigma2) apps = AWGNdemapper(y, alphabet, sigma2) xe = xesmd(apps, indices) mi_mb_64.append((H - (xe) / np.log(2))) 256 QAM M = 16 alphabet = np.arange(-15,16,2) alphabet = alphabet / np.sqrt(np.mean(alphabet**2)) indices = np.random.choice(np.arange(M), n) symbols = alphabet[indices] print('Power: ',np.mean(np.square(symbols))) mi_256 = [] for snrdB in SNR_dBs: sigma2 = 1/(10**(snrdB/10)) sigma2 = sigma2 y = AWGN_channel(symbols, sigma2) apps = AWGNdemapper(y, alphabet, sigma2) xe = xesmd(apps, indices) mi_256.append(2*(4 - (xe) / np.log(2))) Plot plt.rcParams[‘figure.figsize’] = [8, 6] plt.plot(SNR_dBs, mi_16, label = ‘16QAM’) plt.plot(SNR_dBs, mi_64, label = ‘64QAM’) plt.plot(SNR_dBs, mi_mb_64, label = ‘64-MB’) plt.plot(SNR_dBs, mi_256, label = ‘256QAM’) plt.plot(SNR_dBs, np.log2(1+10**(SNR_dBs/10)), color=‘black’, label=‘Capacity’) plt.legend() plt.grid() plt.title(‘AIR of QAM constellation’) plt.ylabel(bits per channel use’) plt.xlabel(‘SNR in dB’) tikzplotlib.save(“QAM_MI.tex”) SNR_dBs = np.arange(5,25) plt.plot(SNR_dBs, np.log2(1+10**(SNR_dBs/10)), color=‘black’, label=‘ C ( P / σ 2 ) C(P/σ 2 )) plt.plot(SNR_dBs, np.log2(1+10**(SNR_dBs/10)) - 0.5np.log2((np.pinp.e)/6) , linestyle=‘dashed’, color=‘C1’, label=‘ C ( P / σ 2 ) − 1 2 log ⁡ 2 π e 6 C(P/σ 2 )− 2 1 ​ log 2 ​ 6 πe ​ ’) plt.grid() plt.ylabel(bits per channel use’) plt.xlabel(‘SNR in dB’) plt.xlim([5, 25]) plt.ylim([1, 8]) plt.title(‘AWGN channel capacity gap’) plt.legend() tikzplotlib.save(“SNR_GAP.tex”) f = lambda x: -np.log10(x) P = 0.4 p1 = my_bisection(f, 0.2, 0.8, P, 0.1) print(“P1 =”, p1) p01 = my_bisection(f, 0.2, 0.8, P, 0.01) print(“P01 =”, p01) print(“f(r1) =”, f(p1)) print(“f(r01) =”, f(p01)) 解释代码,并进行注释,请注意,可以对代码进行规范化,但不要修改原本的结构。另外,将原本的信噪比SNR_dBs = np.arange(5,22)修改为仅包含5,10,15,20.增加星座点可视化,可参考下列代码: 星座图可视化 plt.figure(figsize=(4, 4)) 计算二维网格点(实部+虚部,本例为实数调制) alph = alphabet_norm.detach().numpy() a = np.array([(d, c) for c in np.flip(alph) for d in alph]) 计算联合概率 joint_probs = (probs.reshape(-1, 1) * probs.reshape(1, -1)).flatten().detach().numpy() 绘制散点图(点大小表示概率) plt.scatter(a[:, 0], a[:, 1], s=joint_probs * 2000, alpha=0.6) plt.title(“Constellation Diagram”) plt.xlabel(“In-phase”) plt.ylabel(“Quadrature”) 保存为TikZ格式(用于LaTeX文档) tikzplotlib_save(f"aref_pcs_{SNR_dB}dB.tex") plt.show()
08-13
这是一道编程竞赛目大意是:给定两个长度相同的二进制字符串 a 和 b,要求通过一系列操作将 a 转换为 b,最多允许进行 2n 次操作。操作规则是选择 a 的一个前缀,同时对前缀中的每一位进行反转(0 变 1,1 变 0),并将前缀的顺序反转。要求输出转换所需的最少操作数及每次操作的前缀长度。 ### 输入格式: - 第一行一个整数 t,表示测试用例数。 -每个测试用例包括三行:第一行是整数 n,表示字符串长度;接下来两行分别是字符串 a 和 b。 ### 输出格式: - 对每个测试用例,输出一个整数 k(操作次数),后面跟 k 个整数,表示每次操作的前缀长度。 ### 示例: 输入: 1 6 001011 001001 输出: 2 3 6 解释:先对长度为3的前缀操作,将 a 变为011011;再对整个字符串操作,得到目标字符串 b。 ### 翻译后: 这是该问的较难版本。不同版本之间的区别在于 n 的限制和所需操作次数。只有所有版本都被解决时,才能进行 hack。 有两个长度为 n 的二进制字符串 a 和 b(二进制字符串由 0 和 1 组成)。在一次操作中,选择 a 的一个前缀,同时反转前缀中各位的值(0 变 1,1 变 0),并且反转前缀中各位的顺序。 例如,若 a = 001011,选择长度为3的前缀,那么 a 变为 011011。若接着选择整个字符串作为前缀,则 a 变为 001001。 你的任务是,在最多 2n 次操作内将 a 转换为 b。可以证明这是总是可行的。 输入: 第一行包含一个整数 t(1 ≤ t ≤ 1000)——测试用例数。接下来的 3t 行包含各测试用例的描述。 每个测试用例的第一行包含一个整数 n(1 ≤ n ≤ 1e5)——二进制字符串的长度。 接下来的两行包含两个长度为 n 的二进制字符串 a 和 b。 所有测试用例的 n 之和不超过 1e5。 输出: 对于每个测试用例,输出一个整数 k(0 ≤ k ≤ 2n),后面跟 k 个整数 p₁, p₂,…, p_k(1 ≤ p_i ≤ n)。其中 k 是操作次数,p_i 是第 i 次操作选择的前缀长度。
07-09
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值