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

问题

 

该文章的最新版本已迁移至个人博客【比特飞】,单击链接 https://www.byteflying.com/archives/3862 访问。

编写一个程序判断给定的数是否为丑数。丑数就是只包含质因数 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].

示例

该文章的最新版本已迁移至个人博客【比特飞】,单击链接 https://www.byteflying.com/archives/3862 访问。

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种算法实现,以下是这个案例的输出结果:

该文章的最新版本已迁移至个人博客【比特飞】,单击链接 https://www.byteflying.com/archives/3862 访问。

True

分析:

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值