Is this a triangle?-- 7 Kyu

原題

http://www.codewars.com/kata/is-this-a-triangle/train/cpp

題目

Is this a triangle?
implement a method that accepts 3 integer values a, b, c. The method should return true if a triangle can be built with the sides of given length and false in any other case.
(In this case, all triangles must have surface greater than 0 to be accepted).

分析

三邊構(gòu)成三角形條件:任意兩邊之和大于第三邊,任意兩邊之差小于第三邊。
注意:int之和可能溢出

參考答案

namespace Triangle
{
  bool isTriangle(int a, int b, int c)
  {
    long la(a),lb(b),lc(c);
    return a>0 and b>0 and c>0 and
           la-lb<lc and la-lc<lb and lb-lc<la and
           la+lb>lc and la+lc>lb and lb+lc>la;      
  }
};

說明

本問題非常簡單,但是要注意參數(shù)的特殊情況。

  1. 負(fù)值和0值的情況,需要把這兩種情況排除。
  2. 參數(shù)是整型極大值的情況,兩個(gè)整型極大值會(huì)溢出。所以要把int轉(zhuǎn)long

其它

可以使用如下方式避免特殊情況。

bool isTriangle(int a, int b, int c){
    return a-b<c and a-c<b and b-c<a;      
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容

  • 背景 一年多以前我在知乎上答了有關(guān)LeetCode的問題, 分享了一些自己做題目的經(jīng)驗(yàn)。 張土汪:刷leetcod...
    土汪閱讀 12,769評論 0 33
  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 134,915評論 18 139
  • SwiftDay011.MySwiftimport UIKitprintln("Hello Swift!")var...
    smile麗語閱讀 3,857評論 0 6
  • 校園宣講會(huì),顧名思義,是企事業(yè)單位在校園里中開設(shè)與宣傳、拓展及招聘相關(guān)的主題講座。它向招聘對象傳達(dá)企業(yè)的情況、文化...
    老黃的小太陽閱讀 504評論 0 1
  • 今天是陽歷2017年2月16日,陰歷正月二十,年也過罷節(jié)也過罷,我收到了家在湖北武漢而在浙江嘉興做服裝加工...
    不變的追求閱讀 499評論 2 4