LeetCode:String to Integer (atoi)

本文介绍了一种将字符串转换为整数的方法,包括处理各种输入情况,如空格、正负号及非数字字符等,并确保转换结果处于整数范围内。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Implement atoi to convert a string to an integer.

Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases.

Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front.

Requirements for atoi:

The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value.

The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.

If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed.

If no valid conversion could be performed, a zero value is returned. If the correct value is out of the range of representable values, INT_MAX (2147483647) or INT_MIN (-2147483648) is returned. 


#include<iostream>
#include<string>
#include<vector>
using namespace::std;


class Solution {
public:
    int atoi(const char *str) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
		int flag1 = 0, sign = 1, int_max = 2147483647, int_min = -2147483648;
		double sum = 0, multi = 1;
		int result = 0;
		vector<int> tmp; 

		for(int i = 0; str[i] != NULL; i++)
		{
			if(tmp.size() == 0 && str[i] == ' ')
				continue;			
			if(str[i] == '+' && str[i+1] >= 48 && str[i+1] <= 57)
			{
				sign = 1;
				continue;
			}
			if(str[i] == '-' && str[i+1] >= 48 && str[i+1] <= 57)
			{
				sign = 0;
				continue;
			}
			if((str[i] < 48 || str[i] > 57) && tmp.size() == 0)
			{
				return 0;
			}
			if((str[i] < 48 || str[i] > 57) && tmp.size() != 0)
			{
				break;								
			}
			if(str[i] >= 48 && str[i] <= 57)
			{
				tmp.push_back(str[i] - 48);
			}

		}

		if(tmp.size() == 0)
		{
			return 0;
		}


		//	for(int x = 0; x < tmp.size(); x++)
		//	{
		//		cout<<tmp[x];
		//	}

			while(tmp.size() != 0)
				{
					sum += tmp.back() * multi;
					tmp.pop_back();				
					multi = multi * 10;
					//cout<<"sum: "<<sum<<endl;
				}
			//cout<<"sum:"<<sum<<endl;
				if(sign == 0)
					sum = sum * -1;
				if(sum > int_max)
				{				
					return int_max;
				}
				if(sum < int_min)
				{
					//cout<<"sum:"<<sum<<endl;
					return int_min;
				}
					result = sum;
				return result;
		
		
		/*
		for(int j = 0; j < tmp.size(); j++)
			cout<<" "<<tmp[j];
*/



        
    }
};



int main()
{
	Solution ss;
	

	cout<<"Result: "<<ss.atoi("+10523538441s")<<endl;
}

Round 2:
class Solution {
public:
    int atoi(string str) {
        bool flag = false;
        stack<int> digits;
        long multi = 1;
        long result = 0;
        bool sign = true;
        for(int i = 0; i < str.size(); i++)
        {
            if(flag == false && str[i] == ' ')
                continue;
            else if(flag == false && (str[i] == '+' || str[i] == '-'))
            {
                if(str[i] == '-')
                    sign = false;
                flag = true;
            }
            else if(str[i] >= '0' && str[i] <= '9')
            {
                if(flag == false)
                    flag = true;
                digits.push(str[i] - '0');
            }
            else
            {
                break;
            }
        }
        if(digits.empty())
            return 0;
        else
        {
            while(!digits.empty())
            {
                result += multi * digits.top();
                multi *= 10;
                digits.pop();
                if((sign == true && result > INT_MAX) || (sign == false && 0-result < INT_MIN))
                    return sign == true ? INT_MAX : INT_MIN;
            }
        }
        return sign == true ? result : 0-result;
        
    }
};

Round 3:
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
        int l1 = 0, l2 = 0;
        ListNode *n1 = headA, *n2 = headB;
        while(n1 != NULL)
        {
            n1 = n1->next;
            l1++;
        }
        while(n2 != NULL)
        {
            n2 = n2->next;
            l2++;
        }
        int abs = std::abs(l1-l2);
        n1 = l1 > l2 ? headA: headB;
        n2 = l1 > l2 ? headB: headA;
        while(abs > 0)
        {
            n1 = n1->next;
            abs--;
        }
        while(n1 != NULL && n2 != NULL)
        {
            if(n1 == n2)
                return n1;
            else
            {
                n1 = n1->next;
                n2 = n2->next;
            }
        }
        return NULL;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值