C++ solution transform int into string


  • 0
    S

    class Solution {

    public:

    int reverse(int x) {
        
    std::string s = std::to_string(x);
    stringstream m;
    int  s1;
    int d;
    int begin=0;
    if (s[0]=='-'){
        begin++;
    }
    int k=s.length()+begin;
    for(int i=begin;i<k/2;i++)
    {
        s1=s[i];
        s[i]=s[k-1-i];
        s[k-1-i]=s1;
    }
    m<<s;
    m>>d;
    //int d=atoi(s.c_str() );
    if (d<=-2147483648 || d>=2147483647){
        return 0;
    }
    return d;

  • -1

    class Solution {
    public:

    int reverse(int x)
    {
    	int xRev = 0;
    	long long xTmp = 0;
    	int tmp = 0;
    	while (x != 0)
    	{
    		tmp = x % 10;
    		xTmp = xTmp * 10 + tmp;
    		x /= 10;
    	}
    
    	if (xTmp > 0x7FFFFFFF || xTmp < (signed int)0x80000000)
    	{
    		xRev = 0;
    	}
    	else
    	{
    		xRev = xTmp;
    	}
    
    	return xRev;
    }
    

    };


  • 0
    S

    I just want to use the string method. Thank you. ^_^


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.