当前位置:网站首页>2311. 小于等于 K 的最长二进制子序列
2311. 小于等于 K 的最长二进制子序列
2022-07-05 08:57:00 【紫菜(Nori)】
思路:
1.从右到左,寻找大于最大值的下标点
2.如果有剩余字符,只记录,为0的字符个数
class Solution {
public:
int longestSubsequence(string s, int k) {
int ans = 0;
// 记录当前总消息
long sum = 0;
// 倒序遍历元素,方便直接从右开始计算数字和
int len = s.size() - 1;
int i = len;
for(; i >= 0; i--){
// 当前位数的2的幂次
int bit = len - i;
if(s[i] == '0'){
// 如果当前的幂次所表示的数字,超过k,则可以直接返回,防止后面出现数字溢出问题
if(k < (sum + pow(2, bit))){
break;
}
// 否则继续
continue;
}
// 如果当前字符为1,则表示可以累加记数
// 当已经累加的数字 > k是跳出循环,当前的i保留在这个位置
if(k < (sum += pow(2, bit))){
break;
}
}
// 这个字符串表示的数字完全符合
if(i == -1){
return s.size();
}
// 从右到左,已经符合的长度,
ans = len - i;
// 由于表示的数字已经到达极限,这里只记录为零的字符即可
for(; i >= 0; i--){
if(s[i] == '1'){
continue;
}
ans++;
}
return ans;
}
};
边栏推荐
- Kubedm series-00-overview
- ABC#237 C
- Ros- learn basic knowledge of 0 ROS - nodes, running ROS nodes, topics, services, etc
- Chris LATTNER, the father of llvm: why should we rebuild AI infrastructure software
- Codeworks round 681 (Div. 2) supplement
- [beauty of algebra] singular value decomposition (SVD) and its application to linear least squares solution ax=b
- JS asynchronous error handling
- Solutions of ordinary differential equations (2) examples
- C#图像差异对比:图像相减(指针法、高速)
- RT-Thread内核快速入门,内核实现与应用开发学习随笔记
猜你喜欢
生成对抗网络
Introduction Guide to stereo vision (3): Zhang calibration method of camera calibration [ultra detailed and worthy of collection]
Ros-11 common visualization tools
2020 "Lenovo Cup" National College programming online Invitational Competition and the third Shanghai University of technology programming competition
[code practice] [stereo matching series] Classic ad census: (4) cross domain cost aggregation
It cold knowledge (updating ing~)
Install the CPU version of tensorflow+cuda+cudnn (ultra detailed)
[beauty of algebra] singular value decomposition (SVD) and its application to linear least squares solution ax=b
Summary of "reversal" problem in challenge Programming Competition
编辑器-vi、vim的使用
随机推荐
驾驶证体检医院(114---2 挂对应的医院司机体检)
Chris LATTNER, the father of llvm: why should we rebuild AI infrastructure software
Add discount recharge and discount shadow ticket plug-ins to the resource realization applet
File server migration scheme of a company
Introduction Guide to stereo vision (3): Zhang calibration method of camera calibration [ultra detailed and worthy of collection]
Array, date, string object method
[daily training] 1200 Minimum absolute difference
C#图像差异对比:图像相减(指针法、高速)
图解网络:什么是网关负载均衡协议GLBP?
[Niuke brush questions day4] jz55 depth of binary tree
kubeadm系列-00-overview
什么是防火墙?防火墙基础知识讲解
Confusing basic concepts member variables local variables global variables
2020 "Lenovo Cup" National College programming online Invitational Competition and the third Shanghai University of technology programming competition
Pytorch entry record
编辑器-vi、vim的使用
It cold knowledge (updating ing~)
容易混淆的基本概念 成员变量 局部变量 全局变量
Halcon affine transformations to regions
Kubedm series-00-overview