1. Number of 1 Bits My Submissions Question Solution
这道题本来很简单的,但是在测试中参数int的值会越界,我也不知道是怎么穿进去的
public class Solution {
// you need to treat n as an unsigned value
public int hammingWeight(int n) {
int count = 0;
for(int i=1; i<33; i++){
if(((n>>i) & (1)) != 0){
count++;
}
}
return count;
}
}
2. House Robber 这道题用的是一维DP
public class Solution {
public int rob(int[] num) {
if(num==null || num.length==0)
return 0;
int n = num.length;
int[] dp = new int[n+1];
dp[0]=0;
dp[1]=num[0];
for (int i=2; i<n+1; i++){
dp[i] = Math.max(dp[i-1], dp[i-2]+num[i-1]);
}
return dp[n];
}
}
public class Solution {
public boolean isHappy(int n) {
HashSet<Integer> set = new HashSet<Integer>();
while(!set.contains(n)){
set.add(n);
n = sum(getDigits(n));
if (n == 1)
return true;
}
return false;
}
public int sum(int[] arr){
int sum = 0;
for(int i: arr){
sum = sum + i*i;
}
return sum;
}
public int[] getDigits(int n){
String s = String.valueOf(n);
int[] result = new int[s.length()];
int i=0;
while(n>0){
int m = n%10;
result[i++] = m;
n = n/10;
}
return result;
}
}
4. Remove Linked List Elements 链表删除元素
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode removeElements(ListNode head, int val) {
ListNode helper = new ListNode(0);
helper.next = head;
ListNode p = helper;
while(p.next != null){
if(p.next.val == val){
ListNode next = p.next;
p.next = next.next;
}else{
p = p.next;
}
}
return helper.next;
}
}