Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save SuryaPratapK/b3cdcb5f87f0f00a5d1f79d32d4d85db to your computer and use it in GitHub Desktop.
Save SuryaPratapK/b3cdcb5f87f0f00a5d1f79d32d4d85db to your computer and use it in GitHub Desktop.
class Solution {
public:
int longestSubsequence(string s, int k) {
int n = s.size();
//Step-1: Keep all set bits until value exceeds k
long long val = 0;
int i=0;
while(i<min(n,32)){
if(s[n-i-1]=='1'){
long long power = pow(2,i);
if(val + power > k)
break;
val += power;
}
i++;
}
//Step-2: Count the removed bits
int removed_count = 0;
while(i<n){
if(s[n-i-1]=='1')
removed_count++;
i++;
}
return n-removed_count;
}
};
/*
//JAVA
class Solution {
public int longestSubsequence(String s, int k) {
int n = s.length();
// Step-1: Keep all set bits until value exceeds k
long val = 0;
int i = 0;
while (i < Math.min(n, 32)) {
if (s.charAt(n - i - 1) == '1') {
long power = (long) Math.pow(2, i);
if (val + power > k) {
break;
}
val += power;
}
i++;
}
// Step-2: Count the removed bits
int removed_count = 0;
while (i < n) {
if (s.charAt(n - i - 1) == '1') {
removed_count++;
}
i++;
}
return n - removed_count;
}
}
#Python
class Solution:
def longestSubsequence(self, s: str, k: int) -> int:
n = len(s)
# Step-1: Keep all set bits until value exceeds k
val = 0
i = 0
while i < min(n, 32):
if s[n - i - 1] == '1':
power = 2 ** i
if val + power > k:
break
val += power
i += 1
# Step-2: Count the removed bits
removed_count = 0
while i < n:
if s[n - i - 1] == '1':
removed_count += 1
i += 1
return n - removed_count
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment