判断一个数是否为回文数或者打印特定范围的回文数。

回文数:设n是一任意自然数。若将n的各位数字反向排列所得自然数n1与n相等,则称n为一回文数。

 1 public class PracticeDemo {
 2     /**
 3      *@Function: isPalindrome
 4      *@Description:判断1个数是否为回文数(一个数正着读和反着读一样)。
 5      *@Input:一个整型数
 6      *@Return_Type: boolean
 7      *@Return:判断是否为回文花数(true和false)
 8      *@Other:利用字符串知识点来解决
 9      *2020年2月18日:
10       *上午11:54:15
11      */
12     public static boolean isPalindrome(int x)
13     {
14         String s = ""+x; //java支持字符串相加
15         for(int i = 0;i < s.length()/2;i++)
16         {
17             if(s.charAt(i) != s.charAt(s.length()-1-i))//提取前后位置的字符串
18             return false;
19         }
20         return true;
21     }
22     //同上
23     public static boolean isPalindrome1(int x)
24     {
25        if(x < 0)
26        {
27          return false;
28        }
29        int temp = 1;
30        int a = x;
31        while(a >= 10)//1001
32         {
33           temp *= 10; //高位权值
34           a /= 10; //为找到最高权值做铺垫
35         }
36      
37        while(x != 0) 
38         {
39           if(x%10 != x/temp) //最后一位和最高位比较
40            {
41              return false;
42            }
43           x = x % temp / 10; //x变为去掉最前面一位和最后一位
44           temp /= 100;//每次去掉两个数,位权值减低100
45         }
46        return true; 
47      }
48    /**
49     *@Function:PrintPalindrome
50     *@Description:打印所输进范围的回文数
51     *@Input:两个整型数,表示x~y范围
52     *@Output:x~y范围的回文数
53     *@Return_Type:void
54     *@Return:void
55     *@Other:利用字符串
56     *2020年2月18日:
57     *下午12:04:15
58    */
59    public static void PrintPalindrome(int x ,int y)
60     {
61       for(int i = x;i < y+1;i++) 
62        {   
63          int is = 1;//标志数 或者标号M(在第一个for前面M:)
64          String l = "" + i; 
65          for(int j = 0;j < l.length()/2;j++)
66          {
67             if(l.charAt(j) != l.charAt(l.length()-1-j))
68             {
69                 is = -1;
70              //continue M; 直接跳到M标号处
71             }
72          }
73          if(-1 != is)
74             System.out.print(i+" ");
75       }
76    }
77  public static void main(String[] args) {
78     Scanner input = new Scanner(System.in);
79     System.out.println("请您输入所要求回文数的范围:");
80     int x = input.nextInt();
81     int y = input.nextInt();
82     //System.out.println(isPalindrome(x));
83     //System.out.println(isPalindrome1(x));
84     PrintPalindrome(x,y);
85   }
86  }

猜你喜欢

转载自www.cnblogs.com/YangK123/p/12325669.html