考研算法第46天: 字符串转换整数 【字符串,模拟】

题目前置知识

c++中的string判空

cpp 复制代码
string Count;
Count.empty(); //正确
Count != null; //错误

c++中最大最小宏

cpp 复制代码
#include <limits.h>

INT_MAX
INT_MIN

字符串使用+发运算将字符加到字符串末尾

cpp 复制代码
string Count;
string str = "liuda";
Count += str[i];

题目概况

AC代码

cpp 复制代码
#include <iostream>
#include <cstring>
#include <limits.h>
using namespace std;

long long int count = 0;
string Count;
int findCount(string &str){
	int bit = 1;
	int n=str.size();
    for(int i=0;i<n;i++){
        if(str[i]>='0'&&str[i]<='9'){
            Count += str[i];
        }else if(!Count.empty()){
        	break;
		}
    }
    if(!Count.empty()){
    for(int i=Count.size()-1;i>=0;i--){
        count += (Count[i]-'0')*bit;
		bit = bit * 10;	
	} 
//这里如果题目有负数的话,就不能这么做了。
	 if(count<=INT_MAX&&count>=0){
       return count;
    }
    }

    return -1;
}

int main(){
    string str;
    cin>>str;
    int result=findCount(str);
    cout<<result;
    return 0;
}
相关推荐
wanderist.14 小时前
Lambda表达式在算法竞赛中的应用
java·开发语言·算法
稚南城才子,乌衣巷风流14 小时前
支配树(Dominator Tree)详解:概念、算法与应用
算法
稚南城才子,乌衣巷风流15 小时前
动态开点:原理、实现与应用场景
数据结构·算法
yyds_yyd_1008615 小时前
1464. 数组中两元素的最大乘积(2026.07.27)
数据结构·c++·算法·leetcode
KaMeidebaby16 小时前
卡梅德生物技术快报 | 核酸适配体文库测序:核酸适配体文库测序的技术原理、实验流程与数据解析
前端·网络·数据库·人工智能·算法
geovindu17 小时前
CSharp: Breadth First Search Algorithm and Depth First Search Algorithm
开发语言·后端·算法·c#·.net·搜索算法
ekkoalex18 小时前
训练框架以及算法实现的框架
算法
DFT计算杂谈18 小时前
交错磁研究进展材料物性与交叉应用
数据库·人工智能·python·opencv·算法
玖玥拾18 小时前
LeetCode 26 删除有序数组中的重复项
算法·leetcode
Kina_C18 小时前
LVS负载均衡的十二种核心调度算法
linux·运维·算法·负载均衡·lvs