LeetCode263_263. Ugly numbers

LeetCode263_263. Ugly numbers

1. Description

An ugly number is a positive integer that contains only prime factors 2, 3, and 5.

Given an integer n, please judge whether n is an ugly number. If yes, return true; otherwise, return false.

Example 1:

输入:n = 6
输出:true
解释:6 = 2 × 3

Example 2:

输入:n = 1
输出:true
解释:1 没有质因数,因此它的全部质因数是 {2, 3, 5} 的空集。习惯上将其视作第一个丑数。

Example 3:

输入:n = 14
输出:false
解释:14 不是丑数,因为它包含了另外一个质因数 7 。

hint:

-2 to the 31st power <= n <= 2 to the 31st power - 1

Two, solution

Method 1: Just keep dividing by 2 3 5 until the result is 1

    //AC Your runtime beats 61.46 % of java submissions.
    // 1012 / 1012 test cases passed.	Status: Accepted	Runtime: 4 ms
    //思路就是就是一直除以 2 3 5 直到结果是1即可
    public boolean isUgly(int num) {
    
    
        boolean res = false;
        if (num <= 0) {
    
    
            return false;
        } else if (num == 1) {
    
    //这个判断也可以不单独写。因为1本身题目就定义为Ugly Number
            res = true;
        } else {
    
    
            while (num % 2 == 0)
                num /= 2;
            while (num % 3 == 0)
                num /= 3;
            while (num % 5 == 0)
                num /= 5;
            if (num == 1)
                res = true;
        }
        return res;
    }

LeetCode 217. Existence of Duplicate Elements
LeetCode 229. Majority II
LeetCode 231. Powers of 2
LeetCode 234. Palindrome Linked
List LeetCode 237. Delete Nodes in a Linked List
LeetCode 242. Valid Alphabetic Words
LeetCode 257. All Paths in a Binary Tree
LeetCode 258 . Add everyone
LeetCode 263. Ugly numbers
LeetCode 268. Missing numbers



Disclaimer:
        The copyright of the topic belongs to the original author. The code and related statements in the article are written by myself based on my understanding. The relevant pictures in the article are screenshots from my own practice and pictures corresponding to related technologies. If you have any objections, please contact to delete them. grateful. Reprint please indicate the source, thank you.


By luoyepiaoxue2014

Station B: https://space.bilibili.com/1523287361 Click to open the link
Weibo: http://weibo.com/luoyepiaoxue2014 Click to open the link

Guess you like

Origin blog.csdn.net/luoyepiaoxue2014/article/details/129673447