考研算法第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;
}
相关推荐
疯狂的喵5 小时前
C++编译期多态实现
开发语言·c++·算法
scx201310045 小时前
20260129LCA总结
算法·深度优先·图论
2301_765703145 小时前
C++中的协程编程
开发语言·c++·算法
m0_748708055 小时前
实时数据压缩库
开发语言·c++·算法
小魏每天都学习6 小时前
【算法——c/c++]
c语言·c++·算法
智码未来学堂6 小时前
探秘 C 语言算法之枚举:解锁解题新思路
c语言·数据结构·算法
Halo_tjn6 小时前
基于封装的专项 知识点
java·前端·python·算法
春日见6 小时前
如何避免代码冲突,拉取分支
linux·人工智能·算法·机器学习·自动驾驶
副露のmagic7 小时前
更弱智的算法学习 day59
算法
u0109272717 小时前
C++中的RAII技术深入
开发语言·c++·算法