[LeetCode By Go 78]263. Ugly Number

题目

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
}
    原文作者:miltonsun
    原文地址: https://www.jianshu.com/p/91da240bb80e
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞