careercup-中等難度 17.4

來源:互聯網
上載者:User

標籤:style   blog   io   ar   color   os   使用   sp   div   

17.4 編寫一個方法,找出兩個數字中最大的那一個。不得使用if-else或其他比較子。

解法:

我們可以通過一步步的分析來將需要用到的if-else和比較操作符去掉:

If a > b, return a; else, return b.If (a - b) < 0, return b; else, return a.If (a - b) < 0, 令k = 1; else, 令k = 0. return a - k * (a - b).令z = a - b. 令k是z的最高位,return a - k * z.

當a大於b的時候,a-b為正數,最高位為0,返回的a-k*z = a;當a小於b的時候, a-b為負數,最高位為1,返回的a-k*z = b。可以正確返回兩數中較大的。

另外,k是z的最高位(0或1),我們也可以用一個數組c來存a,b,然後返回c[k]即可。

代碼如下:

#include<iostream>using namespace std;int max1(int a,int b){    int s=a-b;    int k=s>>31&1;    return a-k*s;}int max2(int a,int b){    int c[2]={a,b};    int k=(a-b)>>31&1;    return c[k];}int main(){    cout<<max2(2,55)<<endl;}

 

careercup-中等難度 17.4

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.