Non-array method:
Core: Turn a number from left to right upside down (reverse order) into a new number, and judge whether it is the same as the original number
Difficulty: Flashback output cannot meet the requirement of forming new numbers
scanf("%d",&n);
while(n)
{
print("%d",n%10);
n/10
}
Solution: After finding each digit, multiply by 10 and keep shifting to the left (operation)
For example, 1234. (See above for the operation process)
Find 4, after the operation , become 40, add the next digit (3), become 43
After the operation , it becomes 430, plus the next digit (2), becomes 432
After the operation , it becomes 4320, plus the next digit (1), becomes 4321. (Complete the new number)
Specific code:
#include<stdio.h>
int main()
{
int mx = 0;//mx为旧数 1
scanf("%d", &mx);
int m = mx;//备份一份旧数,最后与新数做比较 2
int n = 0;;//新数的创建 3
while (m)
{
int x = m % 10;//为了不改变m的值,创建一个x来接收每一位 4
n = n * 10 + x;
m/=10;
}
if (n == mx)
{
printf("%d是对称数 ", mx);
}
else
printf("想得美");
return 0;
}
Note: In order to keep the original value unchanged in the code, a new variable is created for backup (2, 4)
Array method:
Core: store a number in an array, and judge by comparing the first and last elements one by one
Difficulties: 1. To control the cycle of taking the position of the array, and at the same time control the cycle of taking out all the digits of the number
Solution: Add an if in the for loop to achieve dual control
2. In the array, the head element head and the tail element hail are judged one by one (hail--), and the selection of the termination condition
Solution: take a special position, 0 1 2. 2/2=1. 0 1 2 3. 3/2=1.
#include<stdio.h>
int main()
{
int a,tail ,head , i, arr[1000];
int flag = 1;//设置判断符,不更改为0,即是对称数 1
scanf("%d", &a);
int ma = a;//备份
if (a< 10)//对称数起码是二位数
{
return 0;
}
for (i = 0; i < 1000; i++)//可以实现,数组用多少(位)拿多少
{
arr[i] = a % 10;
a /= 10;
if (a == 0) //循环跳出条件,此时for循环中有两个控制条件
break;
}
for (tail = i,head = 0; head <= i / 2; head++)
{
if (arr[head] != arr[tail])
{
flag = 0;//若更改为0,不是对称数 2
break;
}
tail--;
}
if (flag == 1)
printf("%d是对称数", ma);
else
printf("你在想什么?");
return 0;
}
Non-array method: method two
(to be continued)