P1553 數字反轉(升級版)
阿新 • • 發佈:2021-11-18
#include<bits/stdc++.h> using namespace std; /** 0.000009->0.9 0.900000->0.000009 00000.00000->0.0 0/1230000->0/123 不是0也不是0/0000123 000000000->0 1.00 -->1.0 0% --->0% */ //是哪種? int getType(string a) { if (a.find('.') != string::npos) return 2; if (a.find('/') != string::npos) return 3; if (a.find('%') != string::npos) return 4; return 1; } int main() { string a; int i, p, end; cin >> a; if (a == "0") { printf("%d", 0); exit(0); } switch (getType(a)) { case 1: //去掉前導0 i = a.size() - 1; while (a[i] == '0')i--; //輸出 if (i == -1) cout << 0; else while (i >= 0) cout << a[i], i--; break; case 2: p = a.find('.'); //輸出整數部分 i = p - 1; while (a[i] == '0')i--; //輸出大吉 //如果只有一個0 if (i == -1) cout << 0; else while (i >= 0) cout << a[i], i--; //輸出. cout << "."; //小數部分開始 i = a.size() - 1; //跳過後導0 end = p + 1; while (a[end] == '0')end++; if (i < end) cout << 0; else //輸出大吉 while (i >= end) cout << a[i], i--; break; case 3: p = a.find('/'); //分子 i = p - 1; while (a[i] == '0')i--; if (i == -1) cout << 0; //輸出大吉 else while (i >= 0) cout << a[i], i--; //除號 cout << "/"; //分母 i = a.size() - 1; //跳過前導0 while (a[i] == '0')i--; //輸出大吉 while (i > p) cout << a[i], i--; break; case 4: //去掉前導0 i = a.size() - 2; while (a[i] == '0')i--; if (i == -1) cout << 0; //輸出大吉 else while (i >= 0) cout << a[i], i--; //輸出% cout << "%"; break; } return 0; }