Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. You may assume that each input would have exactly one solution, and you may not use the same element twice.
public class Two_sum {
public int[] twoSum(int[] nums, int target) {
for (int i = 0; i < nums.length; i++) {
for (int j = i + 1; j < nums.length; j++) {
if (target - nums[i] == nums[j]) {
return new int[]{i, j};
}
}
}
throw new IllegalArgumentException("No solution");
}
}
Given a signed 32-bit integer x, return x with its digits reversed. If reversing x causes the value to go outside the signed 32-bit integer range [$-2^{31}$, $2^{31} - 1$], then return 0.
public static int reverse(int x) {
long reversed = 0;
int sign = 1;
if (x < 0) { // if x is negative, save that info in sign
sign *= -1;
x *= -1;
}
while (x > 0) {
reversed = reversed * 10 + (x % 10);
x /= 10;
}
if (sign == -1) {
reversed *= sign;
}
if ((reversed > Math.pow(-2, 31)) && (reversed < (Math.pow(2, 31) - 1))) {
return (int) reversed;
}
return 0;
}
Given the head of a sorted linked list, delete all duplicates such that each element appears only once. Return the linked list sorted as well.