如何判斷一個整型數字是不是對稱數字


如何判斷一個整型數字是不是對稱數字(用純C語言實現)

比如輸入是1569651是一個對稱數字,而25則不是一個對稱數字。

有兩種判斷方法:

1. 將輸入的數字分解成一個個數字,然后進行判斷。

2. 將數字的高地位進行互換,然后判斷互換后的數與原來的數是否相等。

 

方法一:數字分解法

 1 /*將input輸入,輸出為一個output數組和input的位數*/
 2 int decompose(int input, int* output)
 3 {
 4     int* decomposeResult = output;
 5     int count = 0, temp = input;
 6 
 7     while(1)
 8     {
 9         int quotient = temp / 10;
10         int remainder = temp % 10;
11         if((quotient != 0) || ((quotient == 0) && (remainder != 0)))
12         {
13             decomposeResult[count] = remainder;
14             temp = quotient;
15             count ++;
16         }
17         else
18             break;
19     }
20     return count;
21 }
 1 /*判斷是否是對稱數字*/
 2 bool isSymmetryDecompose(const int* input, int count)
 3 {
 4     for(int i = 0; i < count /2 ; i++)
 5     {
 6         if(input[i] != input[count - i - 1])
 7         {
 8             return false;
 9         }
10     }
11     return true;
12 }

方法二:數值高地位互換比較法

 1 /*輸入數字高地位互換,輸出為互換后的結果*/
 2 int highAndLowSwap(int input)
 3 {
 4     int temp = input, swap = 0;
 5        /*將輸入的地位按順序換成輸出的高位,比如輸入為12345,那么輸出為54321*/
 6     while(temp)
 7     {
 8         swap = swap * 10 + temp %10;
 9         temp = temp / 10;
10     }
11 
12     return swap;
13 }
/*判斷兩個數字是否相等,相等則是對稱數字,否則不是對稱數字*/
bool isSymmetryHighAndLowSwap(int input, int inputSwap)
{
    if(input == inputSwap)
        return true;
    else
        return false;
}

 

測試代碼:

 1 void main()
 2 {
 3     int input = 123060321;
 4     int decomposeResult[32], swapResult;
 5     int count  = 0;
 6     bool isSymDecomp = false, isSymSwap = false;
 7 
 8     count = decompose(input, decomposeResult);
 9     isSymDecomp = isSymmetryDecompose(decomposeResult, count);
10     swapResult = highAndLowSwap(input);
11     isSymSwap = isSymmetryHighAndLowSwap(input, swapResult);
12 
13     if(isSymDecomp)
14         printf("Is a symmetry number, judge by decompose method!\n");
15     else
16         printf("Not a symmetry number, judge by decompose method!\n");
17     
18     printf("\n");
19     
20     if(isSymSwap)
21         printf("Is a symmetry number, judge by swap method!\n");
22     else
23         printf("Not a symmetry number, judge by swap method!\n");
24     
25     printf("\n");
26     
27     printf("Please print enter to continue ...\n");
28     getchar();
29 }

 

測試結果:

 

源碼下載:

http://download.csdn.net/detail/hudaliquan/9765114


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM