栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

LeetCode //C++ Palindrome Number

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

LeetCode //C++ Palindrome Number

Palindrome Number

 

Given an integer x, return true if x is palindrome integer. An integer is a palindrome when it reads the same backward as forward. For example, 121 is a palindrome while 123 is not.

 
Example 1:

Input: x = 121
Output: true
Explanation: 121 reads as 121 from left to right and from right to left.

Example 2:

Input: x = -121
Output: false
Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.

Example 3:

Input: x = 10
Output: false
Explanation: Reads 01 from right to left. Therefore it is not a palindrome.

Constraints:

− 2 31 < = x < = 2 31 − 1 -2^{31} <= x <= 2^{31} - 1 −231<=x<=231−1

 
Follow up: Could you solve it without converting the integer to a string?

From:LeetCode
Link:https://leetcode.cn/problems/palindrome-number
 

Note: The code runs in the win32 console, and some parts may need to be changed in different IDE environments. IDE: Visual Studio 2010
Solution 1: Ideas:Use the method of reversing the numbers, and then judge whether the reversed numbers are equal to the original numbers. Code:
class Solution {
public:
    bool isPalindrome(int x) {
        double lowerBounds=pow(-2.0, 31.0);
        double uppderBounds=pow(2.0, 31.0)-1;
        if(x<0) {
            return false;
        }
        if(xuppderBounds) {
            return false;
        }
        int temp, num=x;
        double total=0.0;  //Beware of overflow when you reverse the integer.
        while(num!=0) {
            total*=10;
            temp=num%10;
            num=(num-temp)/10;
            total+=temp;
        }
        if(x==total) {
            return true;
        }
        else {
            return false;
        }
    }
};
Full Version:
#include 
#include 
using namespace std;

bool isPalindrome(int x);
int reverseNum(int x);

int main() {
	int number;
	cout<<"Enter the nunber: ";
	cin>>number;
	if(isPalindrome(number)==true)
		cout<<"True"<
	double lowerBounds=pow(-2.0, 31.0);
	double upperBounds=pow(2.0, 31.0)-1.0;
	if(x<0)
		return false;
	if(xupperBounds)
		return false;
	if(x==reverseNum(x))
		return true;
	else
		return false;
}

int reverseNum(int x) {
	int temp, total=0;
	while(x!=0) {
		total*=10;
		temp=x%10;
		x=(x-temp)/10;
		total+=temp;
	}
	return total;
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/913622.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号