Ugly Number

LeetCode Q 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.

Solution

Code: Recursive approach

public boolean isUgly(int n) {
	if (n <= 0) return false;
	else if (n == 1 || n == 2 || n == 3 || n == 5) return true;
	else if (n % 2 == 0) return isUgly(n / 2);
	else if (n % 3 == 0) return isUgly(n / 3);
	else if (n % 5 == 0) return isUgly(n / 5);
	else return false;
}

Code: Iterative approach

public boolean isUgly(int n) {
	if (n <= 0) return false;
	
	while (n >= 2 && n % 2 == 0) n /= 2;
	while (n >= 3 && n % 3 == 0) n /= 3; 
	while (n >= 5 && n % 5 == 0) n /= 5;

	return n == 1;
}

   Reprint policy


《Ugly Number》 by Tong Shi is licensed under a Creative Commons Attribution 4.0 International License
 Previous
Ugly Number II Ugly Number II
LeetCode Q 263 - Ugly Number IIWrite a program to find the n-th ugly number. Ugly numbers are positive numbers whose pri
2019-04-10 Tong Shi
Next 
Missing Number Missing Number
LeetCode Q 268 - Missing NumberGiven an array containing n distinct numbers taken from 0, 1, 2, …, n, find the one that
2019-04-10 Tong Shi
  TOC