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).

分析

三边构成三角形条件:任意两边之和大于第三边,任意两边之差小于第三边。
注意: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;      
  }
};

说明

本问题非常简单,但是要注意参数的特殊情况。

  1. 负值和0值的情况,需要把这两种情况排除。
  2. 参数是整型极大值的情况,两个整型极大值会溢出。所以要把intlong

其它

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

bool isTriangle(int a, int b, int c){
    return a-b<c and a-c<b and b-c<a;      
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 14,360评论 0 33
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 136,264评论 19 139
  • SwiftDay011.MySwiftimport UIKitprintln("Hello Swift!")var...
    smile丽语阅读 9,403评论 0 6
  • 校园宣讲会,顾名思义,是企事业单位在校园里中开设与宣传、拓展及招聘相关的主题讲座。它向招聘对象传达企业的情况、文化...
    老黄的小太阳阅读 3,465评论 0 1
  • 今天是阳历2017年2月16日,阴历正月二十,年也过罢节也过罢,我收到了家在湖北武汉而在浙江嘉兴做服装加工...
    不变的追求阅读 3,414评论 2 4

友情链接更多精彩内容