暑假算法7.6,Day05
第一题
二进制间距
class Solution {
public:
int binaryGap ( int n) {
int ans = 0 , i = 0 , j = INT_MAX;
for ( ; n; n>>= 1 , ++ i)
if ( n% 2 ) ans = max ( ans, i- j) , j = i;
return ans;
}
} ;
第二题
位1的个数
public class Solution {
public int hammingWeight ( int n) {
int count = 0 ;
while ( n != 0 ) {
count += n & 1 ;
n = n >> > 1 ;
}
return count;
}
}
第三题
只出现一次的数字
class Solution {
public:
int singleNumber ( vector< int > & nums) {
int ans = 0 ;
for ( int num: nums) {
ans ^= num;
}
return ans;
}
} ;
第四题
K-th Not Divisible by n
# include <bits/stdc++.h>
using namespace std;
int fun ( int a, int b)
{
return b + ( b - 1 ) / ( a - 1 ) ;
}
int main ( )
{
int t;
cin >> t;
while ( t-- )
{
int n, k;
cin >> n >> k;
cout << fun ( n, k) << endl;
}
return 0 ;
}