当前位置:网站首页>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;
}
};
边栏推荐
- [beauty of algebra] singular value decomposition (SVD) and its application to linear least squares solution ax=b
- Programming implementation of ROS learning 6 -service node
- Halcon Chinese character recognition
- One dimensional vector transpose point multiplication np dot
- ROS learning 1- create workspaces and function packs
- 混淆矩阵(Confusion Matrix)
- 嗨 FUN 一夏,与 StarRocks 一起玩转 SQL Planner!
- IT冷知识(更新ing~)
- [牛客网刷题 Day4] JZ55 二叉树的深度
- Confusing basic concepts member variables local variables global variables
猜你喜欢
Halcon shape_ trans
Redis implements a high-performance full-text search engine -- redisearch
Wechat H5 official account to get openid climbing account
Rebuild my 3D world [open source] [serialization-1]
Use and programming method of ros-8 parameters
Confusing basic concepts member variables local variables global variables
Introduction Guide to stereo vision (2): key matrix (essential matrix, basic matrix, homography matrix)
Rebuild my 3D world [open source] [serialization-3] [comparison between colmap and openmvg]
Yolov4 target detection backbone
微信H5公众号获取openid爬坑记
随机推荐
Multiple linear regression (gradient descent method)
资源变现小程序添加折扣充值和折扣影票插件
How to manage the performance of R & D team?
什么是防火墙?防火墙基础知识讲解
How many checks does kubedm series-01-preflight have
Chris LATTNER, the father of llvm: why should we rebuild AI infrastructure software
Huber Loss
Programming implementation of subscriber node of ROS learning 3 subscriber
Count of C # LINQ source code analysis
C#【必备技能篇】ConfigurationManager 类的使用(文件App.config的使用)
Golang foundation -- map, array and slice store different types of data
golang 基础 —— golang 向 mysql 插入的时间数据和本地时间不一致
Programming implementation of ROS learning 6 -service node
2011-11-21 training record personal training (III)
C [essential skills] use of configurationmanager class (use of file app.config)
AdaBoost use
[beauty of algebra] singular value decomposition (SVD) and its application to linear least squares solution ax=b
Jenkins Pipeline 方法(函数)定义及调用
Solution to the problem of the 10th Programming Competition (synchronized competition) of Harbin University of technology "Colin Minglun Cup"
One dimensional vector transpose point multiplication np dot