Given an integer n
, return true
if it is a power of four. Otherwise, return false
.
An integer n
is a power of four, if there exists an integer x
such that n == 4x
.
Example 1:
Input: n = 16
Output: true
Example 2:
Input: n = 5
Output: false
Example 3:
Input: n = 1
Output: true
Solution:
The easiest way how to solve this problem is to divide N on 4 and that is it. We will iterate again and again till our number is bigger than 1.
public boolean isPowerOfFour(int n) {
if (n == 0){
return false;
}
while(n != 1){
if (n % 4 != 0){
return false;
}
n /= 4;
}
return true;
}
But also we can use recursion:
public boolean isPowerOfFour(int n) {
return check(n, 1);
}
boolean check(int n, long value) {
if (value >= n) return n == value;
return check(n, value * 4);
}
And sure, we can solve it with math, but I don’t want to share it with you. Because for me, you usually cannot find a mathematical solution without solving this problem before.
Does it clear? Write your comments.
ok ok and out next problem for today
s
, reverse only all the vowels in the string and return it.'a'
, 'e'
, 'i'
, 'o'
, and 'u'
, and they can appear in both cases.
Example 1:
Input: s = "hello"
Output: "holle"
Example 2:
Input: s = "leetcode"
Output: "leotcede"
Solution:
To solve this problem, we will use the popular technique of two-pointers.
The main idea of solving problems like this -- is to understand base techniques and use them later in medium and hard problems.
We are going to prepare a vowel dictionary. Then we can iterate in both directions. If both pointers stay on the vowels we can swap them. And continue our direction.
public String reverseVowels(String s) {
Set<Character> dict = new HashSet<>();
dict.add('a');
dict.add('A');
dict.add('e');
dict.add('E');
dict.add('i');
dict.add('I');
dict.add('o');
dict.add('O');
dict.add('u');
dict.add('U');
int reader = 0;
int writer = s.length() - 1;
StringBuilder sb = new StringBuilder(s);
while (reader < writer) {
if(!dict.contains(s.charAt(reader))){
reader ++;
}
if (!dict.contains(s.charAt(writer))){
writer--;
}
if (dict.contains(s.charAt(reader)) && dict.contains(s.charAt(writer))){
char tmp = s.charAt(reader);
sb.setCharAt(reader++, s.charAt(writer));
sb.setCharAt(writer--, tmp);
}
}
return sb.toString();
}
Does it clear? Write your comments.