难度:中等。
关键在于十进制转二进制的方法。还要注意三个数的二进制可能不一样长。
正确解法:
class Solution {
string DectoBin(int a){
string s = "";
while(a){
s += char(a % 2 + '0');
a /= 2;
}
return s;
}
public:
int minFlips(int a, int b, int c) {
string as = DectoBin(a);
string bs = DectoBin(b);
string cs = DectoBin(c);
int res = 0;
int an = as.length(), bn = bs.length(), cn = cs.length();
int n = max(an, max(bn, cn));
for(int i = 0; i < n; i++){
int k1 = 0, k2 = 0, k3 = 0;
if(i < an)k1 = int(as[i] - '0');
if(i < bn)k2 = int(bs[i] - '0');
if(i < cn)k3 = int(cs[i] - '0');
if(k3 == 0)res += k1 + k2;
else if(k3 == 1 && k1 == 0 && k2 == 0)res += 1;
}
return res;
}
};
结果: