考研算法第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;
}
相关推荐
Fly Wine20 小时前
Leetcode之有效字母异位词
算法·leetcode·职场和发展
程序员夏末1 天前
【LeetCode | 第七篇】算法笔记
笔记·算法·leetcode
csdn_aspnet1 天前
C/C++ 两个凸多边形之间的切线(Tangents between two Convex Polygons)
c语言·c++·算法
数据皮皮侠1 天前
中国城市间地理距离矩阵(2024)
大数据·数据库·人工智能·算法·制造
3GPP仿真实验室1 天前
深度解析基站接收机核心算法:从 MRC 到 IRC 的空间滤波演进
算法
Boop_wu1 天前
[Java 算法] 动态规划(1)
算法·动态规划
WolfGang0073211 天前
代码随想录算法训练营 Day18 | 二叉树 part08
算法
hanlin031 天前
刷题笔记:力扣第43、67题(字符串计算)
笔记·算法·leetcode
yang_B6211 天前
最小二乘法 拟合平面
算法·平面·最小二乘法
放下华子我只抽RuiKe51 天前
深度学习全景指南:硬核实战版
人工智能·深度学习·神经网络·算法·机器学习·自然语言处理·数据挖掘