美文网首页LeetCode By Go
[LeetCode By Go 78]263. Ugly Num

[LeetCode By Go 78]263. Ugly Num

作者: miltonsun | 来源:发表于2017-08-31 15:16 被阅读5次

题目

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.

解题思路

  1. 小于1的不是丑数
  2. 大于1的时候,如果能被2整除,就循环除以2,直到不能被2整除;同理对3,5执行同样操作
  3. 等于1的话是丑数,不等于1(大于1)说明该数还有其他因子,不是丑数

代码

func isUgly(num int) bool {
    if num < 1 {
        return false
    }

    for ; num > 1 && num % 2 == 0 ; {
        num /= 2
    }

    for ; num > 1 && num % 3 == 0 ; {
        num /= 3
    }

    for ; num > 1 && num % 5 == 0 ; {
        num /= 5
    }

    if num == 1 {
        return true
    }

    return false
}

相关文章

网友评论

    本文标题:[LeetCode By Go 78]263. Ugly Num

    本文链接:https://www.haomeiwen.com/subject/sypqjxtx.html