由于是初学者,实现的方法都很简单,暂时不考虑效率,之后(可能)会更新
1. A+B问题
给出两个整数 aa 和 bb , 求他们的和。
样例
如果 a=1 并且 b=2,返回3。
挑战
显然你可以直接 return a + b,但是你是否可以挑战一下不这样做?(不使用++等算数运算符)
说明
a和b都是 32位 整数么?
是的
我可以使用位运算符么?
当然可以
注意事项
你不需要从输入流读入数据,只需要根据aplusb的两个参数a和b,计算他们的和并返回就行。
思路
考虑进位即可
public class Solution {
/**
* @param a: An integer
* @param b: An integer
* @return: The sum of a and b
*/
public int aplusb(int a, int b) {
// write your code here
if (a == 0){
return b;}
if (b == 0){
return a;}
int sum, add;
sum = a ^ b;
add = (a & b) << 1;
return aplusb(add,sum);
}
}
2. 尾部的零
设计一个算法,计算出n阶乘中尾部零的个数
样例
11! = 39916800,因此应该返回 2
挑战
O(logN)的时间复杂度
思路
public class Solution {
/*
* @param n: An integer
* @return: An integer, denote the number of trailing zeros in n!
*/
public long trailingZeros(long n) {
// write your code here, try to do it without arithmetic operators.
long count = 0L;
while(n > 0){
count = (long) (count + (Math.floor(n / 5)));
n = (long) Math.floor(n / 5);
}
return count;
}
}
6. 合并排序数组 II
合并两个排序的整数数组A和B变成一个新的数组。
样例
给出A=[1,2,3,4],B=[2,4,5,6],返回 [1,2,2,3,4,4,5,6]
挑战
你能否优化你的算法,如果其中一个数组很大而另一个数组很小?
思路
两个指针,每次比较两个数组指针指向元素的大小,小的元素加入新数组,指针后移一位,直到一个数组指针到末尾,另一个数组全部加入新数组。
public class Solution {
/**
* @param A: sorted integer array A
* @param B: sorted integer array B
* @return: A new sorted integer array
*/
public int[] mergeSortedArray(int[] A, int[] B) {
// write your code here
int i = 0;
int j = 0;
List<Integer> result = new ArrayList<Integer>();
while(true){
if(i < A.length && j < B.length){
if(A[i] < B[j]){
result.add(A[i]);
i++;
}else{
result.add(B[j]);
j++;
}
}else{
if (i == A.length){
for(int m = j;m < B.length;m++){
result.add(B[m]);
}
break;
}else{
for(int n = i;n < A.length;n++){
result.add(A[n]);
}
break;
}
}
}
int[] re = new int[result.size()];
for(int k = 0;k < result.size();k++){
re[k] = result.get(k);
}
return re;
}
}
8. 旋转字符串
给定一个字符串和一个偏移量,根据偏移量旋转字符串(从左向右旋转)
样例
对于字符串 “abcdefg”.
offset=0 => “abcdefg”
offset=1 => “gabcdef”
offset=2 => “fgabcde”
offset=3 => “efgabcd”
挑战
在数组上原地旋转,使用O(1)的额外空间
思路
循环取出末尾元素,其余元素前移一位,取出元素置于首位。(注意数组为空的情况)
public class Solution {
/**
* @param str: An array of char
* @param offset: An integer
* @return: nothing
*/
public void rotateString(char[] str, int offset) {
// write your code here
if (str.length != 0){
char temp = 'a';
int l = str.length - 1;
int L = str.length;
if (offset > L){
int n = offset / L;
offset -= n * L;
}
while (offset > 0){
offset--;
temp = str[l];
for(int i = 0;i < l;i++){
str[l - i] = str[l -</