1

LeetCode-263-丑数

 2 years ago
source link: https://segmentfault.com/a/1190000040672687
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

LeetCode-263-丑数

题目描述:给你一个整数 n ,请你判断 n 是否为 丑数 。如果是,返回 true ;否则,返回 false 。

丑数 就是只包含质因数 2、3 和/或 5 的正整数。

示例说明请见LeetCode官网。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/probl...
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

解法一:遍历
  • 首先,如果n等于0,直接返回false。
  • 循环处理将n的质因子2、3、5都除掉,然后循环处理,如果n能够被2~Math.sqrt(n)的任何一个数整除,则返回false;否则,如果n为1、2、3、5中的任何一个数字,返回true,否则返回false。
public class LeetCode_263 {
    public static boolean isUgly(int n) {
        if (n == 0) {
            return false;
        }
        while (n % 2 == 0) {
            n = n / 2;
        }
        while (n % 3 == 0) {
            n = n / 3;
        }
        while (n % 5 == 0) {
            n = n / 5;
        }
        for (int i = 2; i <= Math.sqrt(n); i++) {
            if (n % i == 0) {
                return false;
            }
        }
        if (n == 1 || n == 2 || n == 3 || n == 5) {
            return true;
        } else {
            return false;
        }
    }

    public static void main(String[] args) {
        System.out.println(isUgly(920408890));
    }
}

【每日寄语】 万物之中,希望至美。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK