考研算法第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 分钟前
Trie树相关算法题java实现
java·开发语言·算法
WBluuue20 分钟前
数据结构与算法:树上倍增与LCA
数据结构·c++·算法
bruk_spp37 分钟前
牛客网华为在线编程题
算法
黑屋里的马2 小时前
java的设计模式之桥接模式(Bridge)
java·算法·桥接模式
sin_hielo3 小时前
leetcode 1611
算法·leetcode
李小白杂货铺3 小时前
识别和破除信息茧房
算法·信息茧房·识别信息茧房·破除信息茧房·算法推荐型茧房·观点过滤型茧房·茧房
来荔枝一大筐4 小时前
C++ LeetCode 力扣刷题 541. 反转字符串 II
c++·算法·leetcode
暴风鱼划水4 小时前
算法题(Python)数组篇 | 6.区间和
python·算法·数组·区间和
zl_vslam4 小时前
SLAM中的非线性优-3D图优化之轴角在Opencv-PNP中的应用(一)
前端·人工智能·算法·计算机视觉·slam se2 非线性优化
是苏浙5 小时前
零基础入门C语言之C语言实现数据结构之顺序表应用
c语言·数据结构·算法