classSolution { public: intminOperations(int n){ int i = n; int ret = 0; while(i) { //去除末尾0 while(i && !(i & 1)) i = i >> 1; int t = i; int s = 0; while(t & 1) { t = t >> 1; s++; } if(s >= 2) { ret++; t = t | 1; } else ret++; i = t; } return ret; } };
思路2
DFS
1 2 3 4 5 6 7 8 9 10 11 12
classSolution { public: intdfs(int cnt, int n) { int t = n & (-n); if(n - t == 0) return cnt + 1; returnmin(dfs(cnt+1, n - t), dfs(cnt + 1, n + t)); } intminOperations(int n){ returndfs(0,n); } };