Solution by simple C++


  • 0
    L
    • change x to a positive number and get a sign

    if(x==0)
    {
    return 0;
    }
    if(x<0)
    {
    x=-x;
    Isigned=-1;
    }

    • use len = the length(bit)of x ,and put every bit of x into vector called nums

    len=1+(int)log10(x);
    vector<int> nums(len);
    for(int i=0;i<len;i++)
    {
    nums[i]=x%10;
    x=x/10;
    }

    • change the order nums (considering two special conditions that x=0 and len=2 )

    if(len==2)
    {
    return Isigned*(nums[1]+nums[0]*10);
    }
    for(int i=0,j=len-1;(i!=j)&&(i<j);i++,j--)
    {
    temp=nums[i];
    nums[i]=nums[j];
    nums[j]=temp;
    }

    • calculate the result and check if it is legal

    for(int i=0;i<len;i++)
    {
    result=result+nums[i]*pow(10,i);
    }
    if(Isigned==-1)
    {
    result=-result;
    }
    if((result<=-2147483648)||(result>=2147483648))
    {
    return 0;
    }
    return result;


  • 0
    L

    I am a programm beginner~


Log in to reply
 

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