[C + +] Reverse integer integer Flip __c++

Source: Internet
Author: User

Leetcode original title Link: https://leetcode.com/problems/reverse-integer/


Reverse digits of an integer.

EXAMPLE1:X = 123, return 321
example2:x = -123, return-321 brief analysis: This problem is not difficult, but to pay attention to a few points, such as negative flip or negative, to consider the overflow problem, there is no explanation, but according to the test results, when the data overflow, the return value is 0. Because of the possibility of data overflow, we can not simply use an integer to express this. It can be represented by a larger integer type, such as long, or by a string, which I use. This allows for a larger range of integers to be modified only by modifying some constants.


Implementation code:

Class Solution
{public
:
	int reverse (int x)
	{
		string sx = "";
		int flag = 1;
		if (x >= 0)
		{while
			(x!= 0)
			{
				sx = char (' 0 ' + x%) + SX;
				X/=}
		} else
		{
			flag =-1;
			while (x!= 0)
			{
				sx = char (' 0 '-x%) + SX;
				X/=}
		}
		string sr = "";
		for (int i = 0; i < sx.size (); i++)
		{
			sr = Sx[i] + sr;
		}
		if (Flag > 0 && strcompare (sr, "2147483647"))
		{return
			0;
		}
		if (Flag < 0 && Strcompare (sr, "2147483648"))
		{return
			0;
		}
		int ans = 0;
		for (int i = 0; i < sr.size (); i++)
		{
			ans = ans * ten + (Sr[i]-' 0 ');
		}
		return flag*ans;
	}

	BOOL Strcompare (string s1, string s2)
	{/
		*
		s1 >= S2 return true
		S1 < S2  return false
		*
		/ if (S1.size () > S2.size ()) return
			true;
		else if (s1.size () < S2.size ()) return
			false;
		
		return s1 > s2;
	}
;


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.