Skip to content

Instantly share code, notes, and snippets.

@non-static
Created January 20, 2014 08:19
Show Gist options
  • Save non-static/8516681 to your computer and use it in GitHub Desktop.
Save non-static/8516681 to your computer and use it in GitHub Desktop.
Determine whether an integer is a palindrome. Do this without extra space. http://oj.leetcode.com/problems/palindrome-number/
// PalindromeNumber.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <math.h>
#include <iostream>
using namespace std;
class Solution
{
public:
// Determine whether an integer is a palindrome. Do this without extra space.
bool isPalindrome(int x)
{
// 2147483647
if (x < 0)
return false;
int i = 0;
int j = 9;
bool started = false;
while (i < j)
{
int left = (x / (int)pow(10, j)) % 10;
if ((left == 0) && !started)
{
j--;
continue;
}
else
{
started = true;
}
int right = (x / (int)pow(10, i)) % 10;
if (left != right)
return false;
j--;
i++;
}
return true;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
Solution s;
int input;
bool result;
input = 1;
result = s.isPalindrome(input);
cout << input << " -- " << (result?"true":"false") << endl;
input = -1;
result = s.isPalindrome(input);
cout << input << " -- " << (result ? "true" : "false") << endl;
input = 0;
result = s.isPalindrome(input);
cout << input << " -- " << (result ? "true" : "false") << endl;
input = 11;
result = s.isPalindrome(input);
cout << input << " -- " << (result ? "true" : "false") << endl;
input = 121;
result = s.isPalindrome(input);
cout << input << " -- " << (result ? "true" : "false") << endl;
input = 12;
result = s.isPalindrome(input);
cout << input << " -- " << (result ? "true" : "false") << endl;
input = 123;
result = s.isPalindrome(input);
cout << input << " -- " << (result ? "true" : "false") << endl;
input = 1221;
result = s.isPalindrome(input);
cout << input << " -- " << (result ? "true" : "false") << endl;
input = 12321;
result = s.isPalindrome(input);
cout << input << " -- " << (result ? "true" : "false") << endl;
input = 1000001;
result = s.isPalindrome(input);
cout << input << " -- " << (result ? "true" : "false") << endl;
input = 1000110001;
result = s.isPalindrome(input);
cout << input << " -- " << (result ? "true" : "false") << endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment