/** * @param weight 重物的重量,应该是一个正整数 * @return 是否可使得天秤平衡 */ public static boolean balance(int weight) { if (weight <= 0) { System.out.println("invalid input."); return false; } int origin = weight; //备份 int left = 0; //左边放了什么砝码 int right = 0; //右边放了什么砝码 int i = 0; //判断第i位是0是1还是2。0是最低位 while (weight != 0) { int tmp = weight % 3; if (tmp == 2) { weight += 1; left = left | (1 << i); //对应的二进制位置1 } else if (tmp == 1) { right = right | (1 << i); } i++; weight /= 3; }
//上面已经求得答案了,现在输出验证一下 StringBuilder sbLeft = new StringBuilder("" + origin); int sumLeft = origin; if (left != 0) { int power = 1; while (left != 0) { int value = left & 1; if (value == 1) { sbLeft.append(" + " + power); sumLeft += power; } power *= 3; left = left >> 1; } }
int sumRight = 0; StringBuilder sbRight = new StringBuilder(); if (right != 0) { int m = 1; while (right != 0) { int value = right & 1; if (value == 1) { sbRight.append(" + " + m); sumRight += m; } m *= 3; right = right >> 1; } } System.out.println(sbLeft.toString() + " = " + sbRight.substring((" + ").length()).toString()); System.out.println(sumLeft + "," + sumRight); return sumLeft == sumRight;