將一個字符串轉換成一個整數,要求不能使用字符串轉換整數的庫函數。 數值為0或者字符串不是一個合法的數值則返回0


// test20.cpp : 定義控制台應用程序的入口點。
//

#include "stdafx.h"
#include<iostream>
#include<vector>
#include<string>
#include<queue>
#include<stack>
#include<cstring>
#include<string.h>
#include<deque>

using namespace std;

class Solution {
public:
	int StrToInt(string str) {
		//如果字符串為空,返回-1
		if (str == "")return 0;
		int num=0;//要輸出的數字
		int flag=1;//符號位,0表示負數,1表示正數
		cout << str.find_first_not_of("1234567890+-") << endl;
		if (str.find_first_not_of("1234567890+-") < str.size())  return 0;//如果存在不合法字符

		char ch = str[0];
		int i = 0;
		//判斷符合
		if (ch == '-') 
		{
			flag = 0;//數字為負數
			i = 1;
		}
		else if (ch == '+')
		{
			flag = 1;//為正數
			i = 1;
		}
		else
		{
			i = 0;
		}

		while (i<str.size())
		{
		//	cout << "str[i]:" << str[i] << endl;
			int a = str[i]-48; //char類型和int類型相差48
		//	cout << "a:" << a << endl;
			num = num * 10 + a;
			cout << "num:" << num << endl;
			i++;
		}

		if (flag == 0) num = -num;
		
		return num;
	}
};

int main()
{
	
	Solution so;
	//int count = so.FirstNotRepeatingChar("wangdanwang");
	vector<int> data = { 1,2,3,4,5,5,5,6,7,8};
	int count = so.StrToInt("123");
	cout << count << endl;
	
	
	
	cout << endl;
	return 0;
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM