Leetcode: 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 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;
        }
        return num == 1;
    }
}

Peeking Iterator

Given an Iterator class interface with methods: next() and hasNext(), design and implement a PeekingIterator that support the peek() operation — it essentially peek() at the element that will be returned by the next call to next().

思路是在每次取完当前元素后将下一个元素保存,这样peek以及next时可以直接返回这个元素

class PeekingIterator implements Iterator<Integer> {
    private Integer next;
    private Iterator<Integer> iterator;
	public PeekingIterator(Iterator<Integer> iterator) {
	    this.iterator = iterator;
	    // initialize any member here.
	    if (iterator.hasNext()) {
	        this.next = iterator.next();
	    }
	}

    // Returns the next element in the iteration without advancing the iterator.
	public Integer peek() {
        return next;
	}

	// hasNext() and next() should behave the same as in the Iterator interface.
	// Override them if needed.
	@Override
	public Integer next() {
	    System.out.println(next);
	    Integer result = next;
	    next = iterator.hasNext() ? iterator.next() : null;
	    return result;
	}

	@Override
	public boolean hasNext() {
	    return next != null;
	}
}