Skip to content

Commit f82d816

Browse files
committed
Java solution 273 & 260
1 parent 4b4088d commit f82d816

File tree

2 files changed

+75
-0
lines changed

2 files changed

+75
-0
lines changed

java/_260SingleNumberIII.java

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
/**
2+
* Given an array of numbers nums, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once.
3+
*
4+
* For example:
5+
*
6+
* Given nums = [1, 2, 1, 3, 2, 5], return [3, 5].
7+
*
8+
* Note:
9+
* The order of the result is not important. So in the above example, [5, 3] is also correct.
10+
* Your algorithm should run in linear runtime complexity. Could you implement it using only constant space complexity?
11+
*/
12+
public class _260SingleNumberIII {
13+
public int[] singleNumber(int[] nums) {
14+
int diff = 0;
15+
for (int num : nums) {
16+
diff ^= num;
17+
}
18+
diff &= -diff;
19+
int[] result = { 0, 0 };
20+
for (int num : nums) {
21+
if ((num & diff) == 0) {
22+
result[0] ^= num;
23+
} else {
24+
result[1] ^= num;
25+
}
26+
}
27+
return result;
28+
}
29+
}

java/_273IntegertoEnglishWords.java

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
import javax.swing.text.AbstractDocument.LeafElement;
2+
3+
/**
4+
* Convert a non-negative integer to its english words representation. Given input is guaranteed to be less than 231 - 1.
5+
*
6+
* For example,
7+
* 123 -> "One Hundred Twenty Three"
8+
* 12345 -> "Twelve Thousand Three Hundred Forty Five"
9+
* 1234567 -> "One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven"
10+
*/
11+
public class _273IntegertoEnglishWords {
12+
private static final String[] LESS_THAN_20 = { "", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight",
13+
"Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen",
14+
"Nineteen" };
15+
private static final String[] TENS = { "", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy",
16+
"Eighty", "Ninety" };
17+
private static final String[] THOUSANDS = { "", "Thousand", "Million", "Billion" };
18+
19+
public String numberToWords(int num) {
20+
if (num == 0) {
21+
return "Zero";
22+
}
23+
int i = 0;
24+
String result = "";
25+
while (num > 0) {
26+
if (num % 1000 != 0) {
27+
result = helper(num % 1000) + THOUSANDS[i] + " " + result;
28+
}
29+
num /= 1000;
30+
i++;
31+
}
32+
return result.trim();
33+
}
34+
35+
private String helper(int num) {
36+
if (num == 0) {
37+
return "";
38+
} else if (num < 20) {
39+
return LESS_THAN_20[num] + " ";
40+
} else if (num < 100) {
41+
return TENS[num / 10] + " " + helper(num % 10);
42+
} else {
43+
return LESS_THAN_20[num / 100] + " Hundred " + helper(num % 100);
44+
}
45+
}
46+
}

0 commit comments

Comments
 (0)