考研算法第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;
}
相关推荐
晓1313几秒前
第六章 【C语言篇:结构体&位运算】 结构体、位运算全面解析
c语言·算法
iAkuya6 分钟前
(leetcode)力扣100 61分割回文串(回溯,动归)
算法·leetcode·职场和发展
梵刹古音9 分钟前
【C语言】 指针与数据结构操作
c语言·数据结构·算法
VT.馒头14 分钟前
【力扣】2695. 包装数组
前端·javascript·算法·leetcode·职场和发展·typescript
CoderCodingNo2 小时前
【GESP】C++五级练习题 luogu-P1865 A % B Problem
开发语言·c++·算法
大闲在人2 小时前
7. 供应链与制造过程术语:“周期时间”
算法·供应链管理·智能制造·工业工程
小熳芋2 小时前
443. 压缩字符串-python-双指针
算法
Charlie_lll2 小时前
力扣解题-移动零
后端·算法·leetcode
chaser&upper2 小时前
矩阵革命:在 AtomGit 解码 CANN ops-nn 如何构建 AIGC 的“线性基石”
程序人生·算法
weixin_499771552 小时前
C++中的组合模式
开发语言·c++·算法