• [LeetCode] 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.

    Example 1:

    Input: 6
    Output: true
    Explanation: 6 = 2 × 3

    Example 2:

    Input: 8
    Output: true
    Explanation: 8 = 2 × 2 × 2
    

    Example 3:

    Input: 14
    Output: false 
    Explanation: 14 is not ugly since it includes another prime factor 7.

    Note:

    1. 1 is typically treated as an ugly number.
    2. Input is within the 32-bit signed integer range: [−231,  231 − 1].

    丑数I。题意是判断一个正整数是否为ugly number。ugly number的定义是这个数字只能被2,3,5三者的乘积所得到。

    就按照思路做即可,判断能否被2,3,5整除即可。代码如下

    时间O(n)

    空间O(1)

    JavaScript实现

     1 /**
     2  * @param {number} num
     3  * @return {boolean}
     4  */
     5 var isUgly = function(num) {
     6     if (num === 1) return true;
     7     if (num === 0) return false;
     8     while (num % 2 === 0) num = Math.floor(num / 2);
     9     while (num % 3 === 0) num = Math.floor(num / 3);
    10     while (num % 5 === 0) num = Math.floor(num / 5);
    11     return num === 1;
    12 };

    Java实现

     1 class Solution {
     2     public boolean isUgly(int num) {
     3         if (num == 1) return true;
     4         if (num == 0) return false;
     5         while (num % 2 == 0) num /= 2;
     6         while (num % 3 == 0) num /= 3;
     7         while (num % 5 == 0) num /= 5;
     8         return num == 1;
     9     }
    10 }

    LeetCode 题目总结

  • 相关阅读:
    串口基本知识
    20180826
    20180819
    自动化测试
    说话有重点 测试思维
    学习C语言,在软件测试中如何用?
    PC能替代服务器吗?
    服务器与普通电脑的区别?
    k8s 回滚应用
    k8s Service
  • 原文地址:https://www.cnblogs.com/cnoodle/p/11713145.html
Copyright © 2020-2023  润新知