• 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.

    Analyse: Continuously divide the number by 2, 3, 5. If the remaining number is one, then it's a ugly number. 

    Runtime: 4ms.

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

    Runtime: 8ms.

     1 class Solution {
     2 public:
     3     bool isUgly(int num) {
     4         if(num == 0) return false;
     5         if(num == 1) return true;
     6         
     7         int arr[] = {2, 3, 5};
     8         int index = 0;
     9         while(index < 3){
    10             while(num % arr[index] == 0) num /= arr[index];
    11             index++;
    12         }
    13         
    14         if(num == 1) return true;
    15         return false;
    16     }
    17 };
  • 相关阅读:
    树分治 poj 1741
    堆 poj 2010
    堆 poj 2442
    堆的基本操作
    状态压缩codeforces 11 D
    状态压缩 CSU1129 送货到家
    炮兵阵地 POJ 1185
    状态压缩 HDU4539 郑厂长系列故事——排兵布阵
    状态压缩 HDU 3182
    android手势创建及识别
  • 原文地址:https://www.cnblogs.com/amazingzoe/p/4746958.html
Copyright © 2020-2023  润新知