46.孩子们的游戏
public class Solution {
public int LastRemaining_Solution(int n, int m) {
if(n<1||m<1){
return -1;
}
int num[] = new int[n];
int count = n;
int step = 0;
int i =-1;
while(count>0){
i++;
if(i>=n){
i = 0;
}
if(num[i]==-1){
continue;
}
step++;
if(step==m){
step = 0;
num[i] = -1;
count--;
}
}
return i;
}
}
47.求1+2+3+...+n
利用boolean类型的短路
public class Solution {
public int Sum_Solution(int n) {
int sum = n;
boolean ans = ((n>0)&&(sum+=Sum_Solution(n-1))>0);
return sum;
}
}
48.不用加减乘除做加法
链接:https://www.nowcoder.com/questionTerminal/59ac416b4b944300b617d4f7f111b215
来源:牛客网
首先看十进制是如何做的: 5+7=12,三步走 第一步:相加各位的值,不算进位,得到2。 第二步:计算进位值,得到10. 如果这一步的进位值为0,那么第一步得到的值就是最终结果。 第三步:重复上述两步,只是相加的值变成上述两步的得到的结果2和10,得到12。 同样我们可以用三步走的方式计算二进制值相加: 5-101,7-111 第一步:相加各位的值,不算进位,得到010,二进制每位相加就相当于各位做异或操作,101^111。 第二步:计算进位值,得到1010,相当于各位做与操作得到101,再向左移一位得到1010,(101&111)<<1。 第三步重复上述两步, 各位相加 010^1010=1000,进位值为100=(010&1010)<<1。 继续重复上述两步:1000^100 = 1100,进位值为0,跳出循环,1100为最终结果。
public class Solution {
public int Add(int num1,int num2) {
while(num2!=0){
int temp = num1^num2;
num2 = (num1&num2)<<1;
num1 = temp;
}
return num1;
}
}
49.把字符串转化为整数
public class Solution {
public int StrToInt(String str) {
char []cha = str.toCharArray();
if(cha.length==0){
return 0;
}
int start = 0;
int fin = 0;
if(cha[0]=='+'){
start =1;
fin = 1;
}
if(cha[0]=='-'){
start = 1;
fin = -1;
}
int sum = 0;
for(int i = start;i<cha.length;i++){
if(cha[i]<48||cha[i]>57){
return 0;
}
sum = sum*10+cha[i]-48;
}
return fin==-1?sum*(-1):sum;
}
}
50.数组中重复的数字
import java.util.*;
public class Solution {
// Parameters:
// numbers: an array of integers
// length: the length of array numbers
// duplication: (Output) the duplicated number in the array number,length of duplication array is 1,so using duplication[0] = ? in implementation;
// Here duplication like pointor in C/C++, duplication[0] equal *duplication in C/C++
// 这里要特别注意~返回任意重复的一个,赋值duplication[0]
// Return value: true if the input is valid, and there are some duplications in the array number
// otherwise false
public boolean duplicate(int numbers[],int length,int [] duplication) {
if(length==0){
return false;
}
HashSet<Integer> hash = new HashSet();
for(int x:numbers){
if(hash.contains(x)){
duplication[0]=x;
return true;
}else{
hash.add(x);
}
}
return false;
}
}