[英]How to find if a number is a palindrome?
这是我的代码:
#include <stdio.h>
#include <stdlib.h>
int main()
{
unsigned int n;
unsigned long series[100], beck[100];
int j=0, num=0,temp=0,notflin=0;
printf("Please enter the length_of the series :\n");
printf("Please enter the series :\n");
scanf("%u",&n);
for(unsigned int f=0; f<n; f++)
{ series[f]=0;
scanf("%lu",&series[f]);
}
printf("check");
printf("%u",n);
for(unsigned int i=(n-1); i>=0 ; i--)
{
num=0;
num=series[i];
temp=0;
if (num)
{
while((double) num/10!=0)
{
temp*=10;
temp+=(num%10);
num/=10;
}
}
beck[j]=0;
beck[j]=temp;
j++;
}
unsigned int s=0,d=0;
while(1)
{
unsigned long num1=0, number=0;
number=(series[n-1-d]%10);
num1=(beck[n-1-s]%10);
if (number!=num1)
{
notflin=1;
break;
}
series[n-1-d]/=10;
beck[n-1-s]/=10;
if(beck[n-1-s]==0)
s++;
if(series[n-1-d]==0)
d++;
if (d==(n-1)||s==(n-1))
break;
}
printf(notflin==0? "Yes\n":"No\n");
return 0;
}
我试图将输入输入到unsigned long beck[]
以便最后一个索引中的数字将成为unsigned long series[]
的第一个,然后比较索引中的数字。
当我尝试运行代码时,它会卡住。 有什么问题?
您可以使用以下代码查找数字是否是回文。 如果数字是回文,则该方法返回0,否则返回-1-
public int isPalindrome(int number) {
int temp = number;
int reverseNumber = 0;
int rem = 0;
while (temp != 0) {
int rem = temp % 10;
reverseNumber = reverseNumber * 10 + rem;
temp = temp / 10;
}
// if 'number' and reverse of number is equal means
if (number == reverse) {
return 0;
}
return -1;
}
让我们考虑一种情况:
123321 (输入值)
众所周知,这个数字是回文。 现在,观察一件事,第一个字符(从左侧开始)等于第一个字符(从右侧开始)。 类似地,第二个字符(从左侧)等于第二个字符(从右侧)。 依此类推....如果此属性对于字符串中的每个索引均成立,则该字符串被称为回文。
现在,该优化它了。 如果我们在字符串中间放置一个镜像,镜像的左侧将成为右侧的镜像,从而产生了优化的想法。
现在,使用两个索引: low和high ,其中low指向字符串的最左侧字符, high指向字符串的最右侧字符。 并执行以下操作:
while(low <= high) {
if(value at low index == value at high index) {
low++;
high--;
} else {
break;
}
}
现在,如果low的值较大,则high的值表示字符串为回文(HOW ???)。 想一想,在评论部分让我知道。
您可能会发现此代码段很有用:
#include<stdio.h>
#include<string.h>
char str[100005]={0};
int main() {
printf("Enter a number or string to be verified : ");
scanf("%s",str);
int len = strlen(str);
int low = 0;
int high = len -1;
while(low <= high) {
if(str[low] == str[high]) {
low++;
high--;
} else {
break;
}
}
if(low < high) {
printf("No !!! The input string is not palindorme ");
} else {
printf("Indeed !!! String is palindorme ");
}
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.