Java 简单算法题目练习

算法讲解

算法开胃菜 3或5的倍数

题目要求:
If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
Finish the solution so that it returns the sum of all the multiples of 3 or 5 below the number passed in. Additionally, if the number is negative, return 0 (for languages that do have them).
Note: If the number is a multiple of both 3 and 5, only count it once.

中文翻译 :
如果我们列出所有 10 以下的自然数是 3 或 5 的倍数,我们会得到 3、5、6 和 9。这些倍数之和是 23。
完成该解决方案,使其返回传入数字以下所有 3 或 5 倍数的总和。此外,如果数字为负数,则返回 0(对于具有负数的语言)。
注:如果数字的倍数都3和5,只计算它一次。

解题思路:首先要求是 3 或 5 的倍数,所以我们可以通过取余来判断该数字是否满足这个条件,判断表达式为number % 3 == 0 || number % 5 == 0,完成判断之后我们可以用一个 sum来存放累加的结果。
所以该方法为:

public class Solution {
  public int solution(int number) {
    int sum = 0;
    for(int i = 0;i <= number;i++)
      if(i % 3==0 || i % 5 == 0)
        sum += i;
    return sum;
  }
}

我们来测试一下是否能成功,通过Junit来进行测试。
在这里插入图片描述
测试结果:
在这里插入图片描述
测试通过了,说明我们的算法没有问题。
当然我们不满足于一种解决方案,我们可以看看是否有其他解法

import java.util.stream.*;
public class Solution {
  public int solution(int number) {
    return IntStream.range(3, number).filter(n -> n % 3 == 0 || n % 5 == 0).sum();
  }
}

讲解:
通过IntStreamrange方法生成一个从3到number(因为0,1,2都不符合条件,所以我们直接从3开始)的有序串行流,可以理解为我们的for循环,filter方法则是将filter方法返回的false的元素从流中去除,只留下true的元素,括号内是我们的判断表达式,筛选之后通过.sum()方法进行统计所有元素之和,就可以得到我们的结果了。

题目二 Exes and Ohs

题目要求:
Check to see if a string has the same amount of 'x’s and 'o’s. The method must return a boolean and be case insensitive. The string can contain any char.

中文翻译 :
检查字符串是否具有相同数量的“x”和“o”。该方法必须返回一个布尔值并且不区分大小写。字符串可以包含任何字符。

输入/输出示例:

XO("ooxx") => true
XO("xooxx") => false
XO("ooxXm") => true
XO("zpzpzpp") => true // when no 'x' and 'o' is present should return true
XO("zzoo") => false

解题思路:
这个题目是要我们去判断一个字符串里面的‘x’和‘o’的个数时候相同,不区分大小写,如果相同返回true,不同则返回false,首先我们可以将字符串直接转换为小写,可以通过String类中自带的toLowerCase()方法进行转换,如果你想转换为大写也可以通过toUpperCase()方法去转换,然后就可以直接用if去判断两个字母的个数了。

解题方法一:

public class XO {
  public static boolean getXO(String str) {
    int x = 0, o = 0;
    str = str.toLoweCase();
    for(int i = 0; i < str.length(); i++){
      if(str.charAt(i) == '0') o++;
      if(str.charAt(i) == 'x') x++;
    }
    return x == o;
  }
}

方法讲解:
我们先将字符串转换为小写,然后用charAt()取出单个字符判断是否等于x或时候等于o,然后统计个数,return一下x==o的真假即可。

解题方法二:

public class XO {
  public static boolean getXO (String str) {
    str = str.toLowerCase();
    return str.replace("o","").length() == str.replace("x","").length();
  }
}

方法讲解:
同样是先将字符串转换为小写,然后我们通过replace()将x和o都去掉,再通过length()判断剩余的字符串长度是否还相等,如果相等正好说明去掉的x和o的个数也是相等的,因为是同一个字符串,一个去掉了所有的o,一个去掉了所有的x.

当然还有很多其他的方法可以解决这个题目,这里就不一一讲了

题目三 Find The Parity Outlier

题目要求:
You are given an array (which will have a length of at least 3, but could be very large) containing integers. The array is either entirely comprised of odd integers or entirely comprised of even integers except for a single integer N. Write a method that takes the array as an argument and returns this “outlier” N.> 中文翻译 :

您将获得一个包含整数的数组(其长度至少为 3,但可能非常大)。该数组要么完全由奇数组成,要么完全由偶数组成,除了单个整数N。编写一个将数组作为参数并返回这个“异常值”的方法N。

输入/输出示例:

[2, 4, 0, 100, 4, 11, 2602, 36]
Should return: 11 (the only odd number)

[160, 3, 1719, 19, 11, 13, -21]
Should return: 160 (the only even number)

解题思路:
这个题目是需要判断这个数组里面的异常值,如果全是偶数那么这个奇数就是异常值,反之偶数为异常值,奇偶数我们可以通过取余2 是否等于0来判断,然后就可以找到那个异常值了

解题方法一:

public class FindOutlier {

    static int find(int[] integers) {
        int oddcount = 0, odd = 0, evencount = 0, even = 0;
        for (int i : integers) {
            if (i % 2 == 0) {
                even = i;
                evencount++;
            } else {
                odd = i;
                oddcount++;
            }
        }
        return evencount > 1 ? odd : even;
    }
}

方法讲解:
先通过取余判断数组中的每个元素是奇数还是偶数,然后用对应的count进行统计,如果偶数的count大于1则return odd,否则return even即可。

解题方法二:

import java.util.Arrays;

public class FindOutlier{
  static int find(int[] integers) {
    int[] array = Arrays.stream(integers).filter(i -> i % 2 == 0).toArray();  
    return array.length == 1 ? array[0] : Arrays.stream(integers).filter(i -> i % 2 != 0).findAny().getAsInt();
  }
}

方法讲解:
这里的方法和第一题的第二种解法差不多,通过stream流进行操作,把numbers中所有偶数存入array,如果array的长度为1 ,则返回array[0],否则返回Arrays.stream(integers).filter(i -> i % 2 != 0).findAny().getAsInt();重新判断numbers中是奇数的取出来进行return即可。

  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值