263 https://leetcode.com/problems/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.
public bool IsUgly(int num)
{
if (num < 1)
return false;
if (num == 1)
return true;
while (num%2==0)
num /= 2;
while (num%3==0)
num /= 3;
while (num % 5 == 0)
num /= 5;
return num == 1;
}
264 https://leetcode.com/problems/ugly-number-ii/
Write a program to find the n
-th ugly number.
Ugly numbers are positive numbers whose prime factors only include 2, 3, 5
. For example, 1, 2, 3, 4, 5, 6, 8, 9, 10, 12
is the sequence of the first 10
ugly numbers.
Note that 1
is typically treated as an ugly number.
public class Solution
{
public int NthUglyNumber(int n)
{
int count = 0,num=1;
while (count<n)
if (IsUgly(num++))
count++;
return count;
}
public bool IsUgly(int num)
{
if (num < 1)
return false;
if (num == 1)
return true;
while (num%2==0)
num /= 2;
while (num%3==0)
num /= 3;
while (num % 5 == 0)
num /= 5;
return num == 1;
}
}
public int NthUglyNumber(int n)
{
List<int> list=new List<int>();
list.Add(1);
int i2 = 0, i3 = 0, i5 = 0,m,m2,m3,m5;
while (list.Count < n)
{
m2 = list[i2] * 2;
m3 = list[i3] * 3;
m5 = list[i5] * 5;
m = Math.Min(m2, Math.Min(m3, m5));
if (m == m2) i2++;
if (m == m3) i3++;
if (m == m5) i5++;
list.Add(m);
}
return list[n - 1];
}
参考:
http://www.cnblogs.com/grandyang/p/4743837.html