Determine whether an integer is a palindrome. Do this without extra space.
判断一个 整形是不是 回文,不能使用额外的空间
扩展 :(判断 一个字符串是不是回文 ;一个单链表是不是回文;一个栈是不是回文)
//
// PalindromeNumber.c
// Algorithms
//
// Created by TTc on 15/6/6.
// Copyright (c) 2015年 TTc. All rights reserved.
//
#include "PalindromeNumber.h"
#include <ctype.h>
#include <limits.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
/*
分析与解法
回文判断是一类典型的问题,尤其是与字符串结合后呈现出多姿多彩,在实际中使用也比较广泛,而且也是面试题中的常客,所以本节就结合几个典型的例子来体味下回文之趣。
解法一
同时从字符串头尾开始向中间扫描字串,如果所有字符都一样,那么这个字串就是一个回文。采用这种方法的话,我们只需要维护头部和尾部两个扫描指针即可。
*/
/**
*检查字符串s是不是回文, 字符串s的长度为n
直白且效率不错的实现,时间复杂度:O(n),空间复杂度:O(2)。
*/
bool IsPalindrome(const char *s, int n)
{
if (s == NULL || n < 1) return false; // 非法输入
char *front, *back;
front = s;
back = s + n - 1; // 初始化头指针和尾指针
while (front < back) {
if (*front != *back)
return false; // 不是回文,立即返回
++front;
--back;
}
return true; // 是回文
}
static
int reverse(int x) {
long long val = 0;
do
{
val = val * 10 + x % 10;
x /= 10;
} while (x);
return (val > INT_MAX || val < INT_MIN) ? 0 : val;
}
bool
isPalindrome(int x) {
if(x < 0) return false;
if(x < 10) return true;
int y = 0;
y = reverse(x);
return x == y;
}