693. Binary Number with Alternating Bits

693. Binary Number with Alternating Bits

class Solution {
    	public boolean hasAlternatingBits(int n) {
		String binary = Integer.toBinaryString(n);

		for (int i = 1; i < binary.length(); i++) {
			if (binary.charAt(i) == binary.charAt(i - 1))
				return false;
		}

		return true;
	}
}
Advertisements

566. Reshape the Matrix

566. Reshape the Matrix

class Solution {
	public int[][] matrixReshape(int[][] nums, int r, int c) {
		if (nums.length * nums[0].length != r * c)
			return nums;
		int[][] out = new int[r][c];

		boolean[][] visited = new boolean[r][c];

		for (int i = 0; i < nums.length; i++)
			for (int j = 0; j < nums[i].length; j++) {
				searchEmptyPlace: {
					for (int a = 0; a < out.length; a++)
						for (int b = 0; b < out[a].length; b++)
							if (!visited[a][b]) {
								out[a][b] = nums[i][j];
								visited[a][b] = true;
								break searchEmptyPlace;
							}
				}
			}

		return out;
	}
}

496. Next Greater Element I

496. Next Greater Element I

class Solution {
  	public int[] nextGreaterElement(int[] nums1, int[] nums2) {
		int[] out = new int[nums1.length];

		for (int i = 0; i < nums1.length; i++) {
			// search
			int startSearch = 0;
			for (int k = 0; k < nums2.length; k++) {
				if (nums1[i] == nums2[k]) {
					startSearch = k;
					break;
				}
			}
			int outElement = -1;
			for (int j = startSearch + 1; j < nums2.length; j++) {
				if (nums1[i] < nums2[j]) {
					outElement = nums2[j];
					break;
				}
			}
			out[i] = outElement;
		}
		return out;
	}
}

824. Goat Latin

824. Goat Latin

class Solution {
public String toGoatLatin(String S) {
		StringBuilder out = new StringBuilder();

		String[] words = S.split(" ");

		for (int i = 0; i < words.length; i++) {

			if (words[i].charAt(0) == 'a' || words[i].charAt(0) == 'e' || words[i].charAt(0) == 'i'
					|| words[i].charAt(0) == 'o' || words[i].charAt(0) == 'u' || words[i].charAt(0) == 'A'
					|| words[i].charAt(0) == 'E' || words[i].charAt(0) == 'I' || words[i].charAt(0) == 'O'
					|| words[i].charAt(0) == 'U') {
				words[i] += "ma";
			} else {
				words[i] = words[i].substring(1) + words[i].charAt(0)+ "ma";
			}

			for (int j = 1; j <= i + 1; j++)
				words[i] += "a";
			if (i == words.length - 1)// end of sentence
				out.append(words[i]);
			else
				out.append(words[i] + " ");
		}

		return out.toString();
	}
}