首页 > 学院 > 开发设计 > 正文

Leetcode-263 Ugly Number

2019-11-06 06:07:13
字体:
来源:转载
供稿:网友

1.题目

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.

题目意思就是写一个算法,判断一个数是否是丑陋数。丑陋数的相关定义见百度百科  丑陋数 

2.算法

从百科百科中我们知道,如果一个数丑陋,当这个数不为1的时候,对2,3,5相除就会最终为0

    public boolean isUgly(int num) {        // Write your code here        if (num <= 0)        {            return false;        }            while (num % 2 == 0)            {                num /= 2;            }            while (num % 3 == 0)            {                num /= 3;            }             while (num % 5 == 0)            {                num /= 5;            }            if (num == 1)            {                return true;            }            return false;    }


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表