博客
关于我
12.把字符串转换成整数
阅读量:192 次
发布时间:2019-02-27

本文共 840 字,大约阅读时间需要 2 分钟。

题目描述

将一个字符串转换成一个整数,要求不能使用字符串转换整数的库函数。 数值为0或者字符串不是一个合法的数值则返回0

输入描述:

输入一个字符串,包括数字字母符号,可以为空

返回值描述:

如果是合法的数值表达则返回该数字,否则返回0

示例1

输入

"+2147483647"

返回值

2147483647

示例2

输入

"1a33"

返回值

0

 

 

解题思路

1.空字符串-return 0;

2.数字串中存在非法字符-return 0;

str[i]<'0'||str[i]>'9'

3.数字串的正负号处理

flag

return flag*sum

str[i]<'0'||str[i]>'9' -str[0]='0'

sum=0;

sum=sum*10+str[i]-'0';

ASCII码值:0-48 1-49 +-43 --45

 

 

 

class Solution {public:	int StrToInt(string str) {		if (str.empty())			return 0;		int flag = 1;		if (str[0] == '-')		{			flag = -1;			str[0] = '0';//ASCII码值:'-'-45,'0'-48,'9'-57;		}		if (str[0] == '+')		{			flag = 1;			str[0] = '0';//ASCII码值:'+'-43,'0'-48,'9'-57;		}		int sum = 0;		for (int i = 0; i < str.size(); i++)		{			if (str[i]<'0' || str[i]>'9')			{				sum = 0;				break;			}			sum = sum * 10 + str[i] - '0';//ASCII码值:'0'-48,'1'-49,'2'-50		}		return flag*sum;	}};

 

转载地址:http://npbb.baihongyu.com/

你可能感兴趣的文章
No new migrations found. Your system is up-to-date.
查看>>
No qualifying bean of type XXX found for dependency XXX.
查看>>
No qualifying bean of type ‘com.netflix.discovery.AbstractDiscoveryClientOptionalArgs<?>‘ available
查看>>
No resource identifier found for attribute 'srcCompat' in package的解决办法
查看>>
no session found for current thread
查看>>
No static resource favicon.ico.
查看>>
no such file or directory AndroidManifest.xml
查看>>
No toolchains found in the NDK toolchains folder for ABI with prefix: mips64el-linux-android
查看>>
NO.23 ZenTaoPHP目录结构
查看>>
no1
查看>>
NO32 网络层次及OSI7层模型--TCP三次握手四次断开--子网划分
查看>>
NOAA(美国海洋和大气管理局)气象数据获取与POI点数据获取
查看>>
NoClassDefFoundError: org/springframework/boot/context/properties/ConfigurationBeanFactoryMetadata
查看>>
node
查看>>
node exporter完整版
查看>>
node HelloWorld入门篇
查看>>
Node JS: < 一> 初识Node JS
查看>>
Node JS: < 二> Node JS例子解析
查看>>
Node Sass does not yet support your current environment: Linux 64-bit with Unsupported runtime(93)解决
查看>>
Node Sass does not yet support your current environment: Windows 64-bit with Unsupported runtime(72)
查看>>