1、两数之和
输入:nums = [2,7,11,15], target = 9
输出:[0,1]
解释:因为 nums[0] + nums[1] == 9 ,返回 [0, 1] 。
import java.util.Arrays;
class Solution{
public int[] towSum(int target,int[] nums){
int n=nums.length;
for(int i=0;i<n;i++){
for (int j=i+1;j<n;j++){
if(nums[j]==target-nums[i]){
return new int[] {i,j};
}
}
}
return new int[0];
}
}
public class Text1 {
public static void main(String[] args) {
Solution solution =new Solution();
int[] arr={2,7,11,15};
int[] res=solution.towSum(9,arr);
System.out.println(Arrays.toString(res));
}
}
2、回文数
输入:x = 121
输出:true
class Solution {
public boolean isPalindrome(int x) {
if (x < 0 || (x % 10 == 0 && x != 0)) {
return false;
}
int revertedNumber = 0;
while (x > revertedNumber) {
revertedNumber = revertedNumber * 10 + x % 10;
x /= 10;
}
return x == revertedNumber || x == revertedNumber / 10;
}
}
人生苦短,我用python!!!
class Solution(object):
def isPalindrome(self, x):
x=str(x)
if x==x[::-1]:
return True
else:
return False