11、二进制中1的个数
题目描述:输入一个整数,输出该数二进制表示中1的个数。其中负数用补码表示。
解题思路:直接调用API
或者用除以2进行右移,遇1则减1,1的个数+1,负数要考虑int32位前面的符号位全都是1
// 直接调用API
public class Solution {
public int NumberOf1(int n) {
int count = 0;
String result = Integer.toBinaryString(n);
for(int i = 0; i < result.length(); i++) {
char c = result.charAt(i);
if(c == '1') {
count++;
}
}
return count;
}
}
//手撸
public class Solution {
public int NumberOf1(int n) {
if(n == -1) {
return 32;
}
int num = 0;
int count = 0;
while(n != 0) {
if(n % 2 == 0){
n /= 2;
}else {
num++;
if(Math.abs(n) == 1) {
break;
}
n--;
n = n / 2;
}
count++;
}
if(n < 0) {
num += (31 - count);
}
return num;
}
}
12、数值的整数次方
题目描述:给定一个double类型的浮点数base和int类型的整数exponent。求base的exponent次方。
解题思路:直接调用API
或者直接循环乘,注意指数的正负
//直接调用API
public class Solution {
public double Power(double base, int exponent) {
double result = Math.pow(base, exponent);
return result;
}
}
// 手撸代码
public class Solution {
public double Power(double base, int exponent) {
if(exponent == 0) {
return 1;
}else{
double result = 1;
boolean isPositive = true;
if(exponent < 0) {
isPositive = false;
}
exponent = Math.abs(exponent);
while (exponent >= 1) {
result *= base;
exponent--;
}
if(!isPositive) {
result = 1 / result;
}
return result;
}
}
}
13、调整数组顺序使得奇数在偶数前面
题目描述:输入一个整数数组,实现一个函数来调整该数组中数字的顺序,使得所有的奇数位于数组的前半部分,所有的偶数位于数组的后半部分,并保证奇数和奇数,偶数和偶数之间的相对位置不变。
解题思路:拼接两个ArrayList
import java.util.ArrayList;
public class Solution {
public void reOrderArray(int [] array) {
ArrayList<Integer> oddList = new ArrayList<>();
ArrayList<Integer> evenList = new ArrayList<>();
for(int i: array) {
if(i % 2 == 0) {
evenList.add(i);
}else {
oddList.add(i);
}
}
oddList.addAll(evenList);
Object[] list = oddList.toArray();
for(int i = 0; i < array.length ; i++) {
Object o = list[i];
int num = (int)o;
array[i] = num;
}
}
}
14、链表中倒数第K个结点
题目描述:输入一个链表,输出该链表中倒数第k个结点。
解题思路:两次for循环,第一次找出链表长度, 第二次找到所需要的结点
注意 k > length的情况
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
public class Solution {
public ListNode FindKthToTail(ListNode head,int k) {
int length = 0;
ListNode temp = head;
while (temp != null) {
length ++;
temp = temp.next;
}
if(k > length) {
return null;
}
int count = length - k;
ListNode temp2 = head;
while(count > 0) {
count--;
temp2 = temp2.next;
}
return temp2;
}
}
15、翻转链表
题目描述:输入一个链表,反转链表后,输出新链表的表头。
解题思路:前一个node作为后一个node的next
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
public class Solution {
public ListNode ReverseList(ListNode head) {
if(head == null) {
return null;
}
ListNode tail = new ListNode(head.val);
while(head.next != null) {
ListNode node = new ListNode(head.next.val);
node.next = tail;
tail = node;
head = head.next;
}
return tail;
}
}