C#LeetCode刷题之#263-丑数(Ugly Number)

C#LeetCode刷题之#263-丑数(Ugly Number)

问题

编写一个程序判断给定的数是否为丑数。丑数就是只包含质因数 2, 3, 5 的正整数。

输入: 6

输出: true

解释: 6 = 2 × 3

输入: 8

输出: true

解释: 8 = 2 × 2 × 2

输入: 14

输出: false 

解释: 14 不是丑数,因为它包含了另外一个质因数 7。

说明:

  1. 1 是丑数。
  2. 输入不会超过 32 位有符号整数的范围: [−231,  231 − 1]。

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.

Input: 6

Output: true

Explanation: 6 = 2 × 3

Input: 8

Output: true

Explanation: 8 = 2 × 2 × 2

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

示例

public class Program {

    public static void Main(string[] args) {
        var n = 60;
        var res = IsUgly(n);
        Console.WriteLine(res);

        Console.ReadKey();
    }

    private static bool IsUgly(int num) {
        var uglyList = new int[] { 2, 3, 5 };
        foreach(var ugly in uglyList) {
            while(num % ugly == 0 && (num /= ugly) > 0) { }
        }
        return num == 1;
    }

}

以上给出1种算法实现,以下是这个案例的输出结果:

True

分析:

显而易见,以上算法的时间复杂度为: O(n)

本文由 .Net中文网 原创发布,欢迎大家踊跃转载。

转载请注明本文地址:https://www.byteflying.com/archives/3862

发表评论

登录后才能评论