題目鏈接:http://acm.nyist.net/JudgeOnline/problem.php?pid=860
My思路:
先用兩個字符串儲存這兩個實數,然後再用另外兩個字符串儲存去掉符號和前後多余的0後的新"實數",最後只需要比較兩個化簡後的新字符就ok了。
My代碼實現:
1 #include<iostream> 2 using namespace std; 3 string simplify(string s) { //去字符串s的正負號和首尾多余的0 4 string a; 5 int k = s.size()-1, l = 0, t = 0; 6 for(int i = 0; i < s.size(); i++) //判斷是否是小數,如果是小數就需要去除尾部多余的0 7 if(s[i] == '.') { 8 t = 1; 9 break; 10 } 11 if(s[0] == '+' || s[0] == '-') l++; //去除符號 12 while(s[l] == '0') l++; //去除前面多余的0 13 //cout << l << endl; 14 if(t) { //去除後面多余的0 15 while(s[k] == '0') k--; 16 } 17 if(s[k] == '.') k--; 18 //cout << k << endl; 19 while(l <= k) a += s[l++]; 20 return a; 21 } 22 int main() { 23 //string x = "-002540000.0000025000000"; 24 //cout << simplify(x); 25 string A, B, a, b; 26 char fa, fb; 27 while(cin >> A >> B) { 28 a = simplify(A); //去除符號和首尾多余的0 29 b = simplify(B); 30 //cout << a << "\n" << b << endl; 31 if(A[0] != '+' && A[0] != '-') fa = '+'; //正負號拿出來單獨判斷 32 else fa = A[0]; 33 if(B[0] != '+' && B[0] != '-') fb = '+'; 34 else fb = B[0]; 35 if(((fa == '+' && fb == '-') || (fa == '-' && fb == '+')) && (a != "" && b != "")) cout << "NO\n"; //這裡千萬要考慮+0=-0的情況 36 else { 37 int i, p = 1; 38 for(i = 0; i < a.size() && i < b.size(); i++) 39 if(a[i] != b[i]) { 40 cout << "NO\n"; 41 p = 0; 42 break; 43 } 44 if(i == b.size() && i == a.size()) cout << "YES\n"; 45 else if(p) cout << "NO\n"; 46 } 47 } 48 } 代碼實現(點擊展開)開始寫於:2016.7.31 ----志銀