Advertisement
junsangtutor

a038 數字翻轉無struct

Dec 2nd, 2023
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.79 KB | None | 0 0
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. int reverseNumber(int num);
  5.  
  6. int main()
  7. {
  8.     int num;
  9.     cin >> num;
  10.     int reversedNum;
  11.     reversedNum=reverseNumber(num);
  12.  
  13.     cout << reversedNum << endl;
  14.  
  15.     return 0;
  16. }
  17.  
  18. int reverseNumber(int num)
  19. {
  20.     // 當數字為 0 時直接輸出 0
  21.     if (num == 0)
  22.     {
  23.         cout << num << endl;
  24.         return 0;
  25.     }
  26.  
  27.     // 反轉數字同時忽略尾部的零
  28.     int reversedNum = 0;
  29.     while (num > 0)
  30.     {
  31.         int digit = num % 10;  // 獲取最後一位數
  32.         num /= 10;  // 移除最後一位數
  33.  
  34.         if (digit == 0 && reversedNum == 0)
  35.         {
  36.             // 忽略尾部的零
  37.             continue;
  38.         }
  39.  
  40.         reversedNum = reversedNum * 10 + digit; // 將數字反轉
  41.     }
  42.     return reversedNum;
  43.  
  44. }
  45.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement