剑指offer题解46-50(Java)

46.孩子们的游戏

每年六一儿童节,牛客都会准备一些小礼物去看望孤儿院的小朋友,今年亦是如此。HF作为牛客的资深元老,自然也准备了一些小游戏。其中,有个游戏是这样的:首先,让小朋友们围成一个大圈。然后,他随机指定一个数m,让编号为0的小朋友开始报数。每次喊到m-1的那个小朋友要出列唱首歌,然后可以在礼品箱中任意的挑选礼物,并且不再回到圈中,从他的下一个小朋友开始,继续0…m-1报数…这样下去…直到剩下最后一个小朋友,可以不用表演,并且拿到牛客名贵的“名侦探柯南”典藏版(名额有限哦!!_)。请你试着想下,哪个小朋友会得到这份礼品呢?(注:小朋友的编号是从0到n-1)

如果没有小朋友,请返回-1

代码

import java.util.LinkedList;
 
public class Solution {
    public int LastRemaining_Solution(int n, int m) {
        LinkedList<Integer> list = new LinkedList<Integer>();
        for (int i = 0; i < n; i ++) {
            list.add(i);
        }
         
        int bt = 0;
        while (list.size() > 1) {
            bt = (bt + m - 1) % list.size();
            list.remove(bt);
        }
         
        return list.size() == 1 ? list.get(0) : -1;
    }
}

47.求1+。。。+n*

求1+2+3+…+n,要求不能使用乘除法、for、while、if、else、switch、case等关键字及条件判断语句(A?B:C)。

代码

public class Solution {
     public int Sum_Solution(int n) {
        int sum = n;
       //sum<=0是(sum>0)为false ans直接为false 就不会进行后面的判断了,从而实现递归的终止
       //sum已经大于0,但(sum+=Sum_Solution(n-1))>0是为了使后面也是一个判断,从而实现递归
        boolean ans = (sum>0)&&((sum+=Sum_Solution(n-1))>0);
        return sum;
    }
}

48.不用加减乘除做加法*

写一个函数,求两个整数之和,要求在函数体内不得使用+、-、*、/四则运算符号。

代码

参考题解

5+7
第一步:相加各位的值,不算进位,得到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) {
     return num2!=0 ? Add(num1^num2, (num1&num2)<<1) : num1;
    }
}

49.字符串转换为整数

将一个字符串转换成一个整数,要求不能使用字符串转换整数的库函数。 数值为0或者字符串不是一个合法的数值则返回0

输入描述:

输入一个字符串,包括数字字母符号,可以为空

输出描述:

如果是合法的数值表达则返回该数字,否则返回0

示例1

输入

+2147483647
    1a33

输出

2147483647
    0

代码

public class Solution {
    public boolean isNumberic(char c) {
      //判断是否为数字
        if (c == '0' || c == '1' || c == '2' || c == '3' || c == '4' || c == '5' || c == '6' || c == '7' || c == '8' || c == '9') {
            return true;
        } else {
            return false;
        }
    }

    public int StrToInt(String str) {
        if (str.length() == 0) return 0;
        char[] chars = str.toCharArray();
        long ans = 0;
        long m = 1;
        int start = 0;
        if (!isNumberic(chars[0])) {
          //第一个不是数字,有可能是 + 或-
            start = 1;
        }
        for (int i = chars.length - 1; i >= start; i--) {
            if (isNumberic(chars[i])) {
                ans += Integer.parseInt(String.valueOf(chars[i])) * m;
                m *= 10;
            } else {
                return 0;
            }
        }

        if (chars[0] == '-') {
            ans = -ans;
        }
//使用long 防止溢出,然后对溢出值进行判断
        if (ans > Integer.MAX_VALUE || ans < Integer.MIN_VALUE) return 0;
        else return (int) ans;

    }
}

简化代码

public class Solution {
    public int StrToInt(String str) {
      //用正则表达式子进行简化
        if (!(str.matches("[+,-]\\d+") || str.matches("[1-9]\\d*"))) return 0;
        long res = 0;
        int len = str.length();
        int i = len - 1;
        while (i >= 0 && str.charAt(i) <= '9' && str.charAt(i) >= '0') {
            res += (str.charAt(i) - '0') * Math.pow(10, len - 1 - i);
            i--;
        }

        res = (str.charAt(0) == '-' ? -res : res);
        if (res > Integer.MAX_VALUE || res < Integer.MIN_VALUE) return 0;
        return (int) res;

    }
}

50.数组中重复的数字

在一个长度为n的数组里的所有数字都在0到n-1的范围内。 数组中某些数字是重复的,但不知道有几个数字是重复的。也不知道每个数字重复几次。请找出数组中任意一个重复的数字。 例如,如果输入长度为7的数组{2,3,1,0,2,5,3},那么对应的输出是第一个重复的数字2。

代码

简单粗暴,使用set判断是否重复,一旦有就结束

import java.util.HashSet;
import java.util.Set;

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) {
        Set<Integer> set=new HashSet<Integer>();
        for(int i=0;i<length;i++){
            if(set.contains(numbers[i])){
                duplication[0]=numbers[i];
                return true;
            }
            else{
                set.add(numbers[i]);
            }
        }
        return false;

    }
}

总结

  1. 位操作相关知识还是欠缺
  2. 正则表达式需要学习
  3. 问题分析还是急躁
  4. 库函数不够熟练
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值