【ACM-2017四川省賽】A. Simple Arithmetic

題目描述

Given a and b which both fit in 64-bit signed integers, find ⌊ a/b ⌋ where ⌊x⌋ denotes the largest integer which is not larger than x.

Input

The input contains zero or more test cases and is terminated by end-of-file.
Each test case contains two integers a, b.
• −pow(2,63) ≤ a, b < pow(2,63)
• b != 0
• The number of tests cases does not exceed 104
.
Output

For each case, output an integer which denotes the result.

Sample Input

3 2
3 -2
-9223372036854775808 1
-9223372036854775808 -1

Sample Output

1
-2
-9223372036854775808
9223372036854775808

題目分析

這道題目,一眼望去,連我這個小白都覺得簡單,可惜的是總是Runtime Error,看來我是小白是有原因的

題意還是很明瞭,開門見山的告訴你要做什麼,nice

在這裏需要明確的幾個點:
1、數據範圍(這個很重要,我之前一直RE就是這個原因)
2、對於向下取整的理解(正數和負數向下取整的結果分別是什麼)
3、符號位如何處理

解題思路

對於題目中給定的範圍來說,我們用長整型其實是可以裝下的,那麼在參數輸入的時候就用長整型進行接收,但是注意邊界情況,發現邊界很大,那麼我們在運算的時候直接用有符號的長整型進行運算,必定會存在越界的情況(我一直RE其實就是這種情況,),那麼我們可以採用將符號爲進行分開處理,這樣就可以將有符號的強轉爲無符號的,這樣就不會出現越界的情況了。

AC代碼

#include <bits/stdc++.h>
using namespace std;
int main(){
    long long a,b;
    while(cin>>a>>b){
        int fa = -1,fb = -1;
        if(a >= 0){
            fa = 1;
        }
        if(b >= 0){
            fb = 1;
        }
        unsigned long long m = abs(a), n = abs(b), res;
        res = m/n;
        if(fa * fb < 0 && m%n != 0){
            res++;
        }
        if(fa * fb < 0){
            cout<<"-";
        }
        cout<<res<<endl;
    }
    return 0;
}

PS:如有錯誤之處,歡飲dalao留言指正。如有其他建議也歡迎喲。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章