题解 | #懂二进制#
懂二进制
https://www.nowcoder.com/practice/120e406db3fd46f09d55d59093f13dd8
import java.util.*; public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param m int整型 * @param n int整型 * @return int整型 */ public int countBitDiff (int m, int n) { // write code here int tempM = Math.abs(m); int tenpN = Math.abs(n); // 将m和n转化二进制 StringBuffer sbA = new StringBuffer(); StringBuffer sbB = new StringBuffer(); while (tempM > 0) { sbA.append(tempM % 2); tempM = tempM / 2; } while (tenpN > 0) { sbB.append(tenpN % 2); tenpN = tenpN / 2; } // 统计不同位 int count = 0; int len = sbA.length() > sbB.length() ? sbA.length() : sbB.length(); for (int i = 0; i < len; i ++) { if (sbA.length() - 1 < i) { sbA.append('0'); } else if (sbB.length() - 1 < i) { sbB.append('0'); } } for (int i = 0; i < len; i ++) { if (sbA.charAt(i) != sbB.charAt(i)) { count ++; } } return count; } }