LeetCode算法第1篇:263 Ugly Number

来源:互联网 发布:仿58同城网微招聘源码 编辑:程序博客网 时间:2024/06/08 05:38

问题描述:
  Write a program to check whether a given number is an ugly number.

  Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. For example, 6, 8 are ugly while 14 is not ugly since it includes another prime factor 7.

  Note that 1 is typically treated as an ugly number.

代码实现:

bool isUgly(int num) {    if (num <= 0)        return 0;    if (num == 1)        return 1;    while((num >= 2) && (num % 2 == 0))        num /= 2;    while((num >= 3) && (num % 3 == 0))        num /= 3;    while((num >= 5) && (num % 5 == 0))        num /= 5;    return num == 1;}

总结:丑数就是因子只含2,3,5的数,除了能被2,3,5整除外就只能被1和它本身整除了,所以一个丑数不断的被2,3,5除,到最后一定等于1,汗,这么简单的问题竟然想了半天都没想出来,到最后还是得参考别人的代码,看来我这算法能力也是渣到家了,以前学的算法都还给老师了。。。

0 0
原创粉丝点击