返回列表 發帖
不能使用if指令的做法:

#include<iostream>
using namespace std;
int main()
{
    int n;
    while(cin >> n)
    {
       //處理負數(正數及0在這邊變成0)
       int a = (n&2147483648UL)|(4294967295UL*((n&2147483648UL)/2147483648UL));
       //處理正數及0(負數在這邊變成0)
       int b = (((n&2147483648UL)/2147483648UL)^1)*(!!n);
       //上面兩個結果相加就是答案!
       cout << static_cast<int>(a+b) << endl;
       //只需要一行程式的寫法:
       //cout << static_cast<int>((((n&2147483648UL)|(4294967295UL*((n&2147483648UL)/2147483648UL)))+(((n&2147483648UL)/2147483648UL)^1))*(!!n)) << endl;
    }
    return 0;   
}

TOP

使用C內建的常數可以讓程式更清楚且可以避免不同編譯器的int型別資料大小不同導致的錯誤:

#include<iostream>
using namespace std;
int main()
{
    int n;
    while(cin >> n)
    {
       //處理負數(正數及0在這邊變成0)
       int a = (n&(INT_MAX+1))|((INT_MAX*2+1)*((n&(INT_MAX+1))/(INT_MAX+1)));
       //處理正數及0(負數在這邊變成0)
       int b = (((n&(INT_MAX+1))/(INT_MAX+1))^1)*(!!n);
       //上面兩個結果相加就是答案!
       cout << static_cast<int>(a+b) << endl;
       //只需要一行程式的寫法:
       //cout << static_cast<int>((((n&(INT_MAX+1))|((INT_MAX*2+1)*((n&(INT_MAX+1))/(INT_MAX+1))))+(((n&(INT_MAX+1))/(INT_MAX+1))^1))*(!!n)) << endl;
    }
    return 0;   
}

TOP

返回列表