【LeetCode OJ 263】Ugly Number

题目链接: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.

解题思路:上述题意表示,丑数的含义是其因子只包含2,3,5,判断一个数是否为丑数,只需要将这个数与2,3,5循环相除,如果余数为1,则为丑数,否则不是。

示例代码:

public class Solution
{
	  public boolean isUgly(int num)
	  {
	        if (num <= 0) 
	        {
	            return false;
	        }
	        while (num % 2 == 0) 
	        	num /= 2;
	        while (num % 3 == 0) 
	        	num /= 3;
	        while (num % 5 == 0)
	        	num /= 5;
	        if (num == 1) 
	        {
	            return true;
	        } 
	        else
	        {
	            return false;
	        }
	  }
}


你可能感兴趣的:(java,LeetCode)