Codewars征战记录-JAVA篇

Posted Mrlw

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Codewars征战记录-JAVA篇相关的知识,希望对你有一定的参考价值。

无意中发现一个代码题目的网站,做了一个题,深有感触。记下来大牛们的解决思路

渣渣程序员就是我了,我会先列自己的写法,再列大牛的写法,共勉。

题目:传入一个数字n,求3和5的倍数和。如果该数为3和5共同的倍数,则计算一次。

DEMO:传入数字10,求3和5的倍数和,所以需要计算3、5、6、9的和,即23

public int solution(int number) {
      int result = 0;
      
      for (int i = number - 1; i > 0; i--) {
          if (i%5 == 0 || i%3 == 0){
              result = i + result;
          }
      }
     return result;
  }

 

大神例子1,使用 intsteam

public int solution(int number) {
    return IntStream.range(3, number).filter(n -> n % 3 == 0 || n % 5 == 0).sum();
  }

 

还有个不使用循环。。

/*
    The sum of multiples of 3 is 3 + 6 + 9 + ... = 3 (1+2+3+...)
    The sum of mulitples of 5 is 5 + 10 + 15 + ... = 5 (1+2+3+...)
    If we just sum these, we‘ll get double values when a number is divisble by both,
    so we substract the sum of multiples of 15, which is obtained in a similar manner.
    The upper bound cannot be floor function because the inputed number shouldn‘t count.
*/

import java.lang.Math;
public class Solution {
  public int solution(int n) {
    int a = (int) Math.ceil(n/3d) - 1;
    int b = (int) Math.ceil(n/5d) - 1;
    int c = (int) Math.ceil(n/15d) - 1;
    return (3 * a * (a+1) + 5 * b * (b+1) - 15 * c * (c + 1)) / 2;
  }
}

 

 

题目:ATM的密码只能有4或者6位的数字密码组成。写一个方法判断。

首推正则

public static boolean validatePin(String pin) {
  // 自己正则写的不熟悉,用的是:[0-9]{4,4}|[0-9]{6,6}
return pin.matches("\d{4}|\d{6}"); }

 

JDK8写法

 public static boolean validatePin(String pin) {
    if(pin == null) return false;
    if (pin.length() == 4 || pin.length() == 6) 
        return pin.chars().allMatch(Character::isDigit);
    return false;
  }

 

以上是关于Codewars征战记录-JAVA篇的主要内容,如果未能解决你的问题,请参考以下文章

用itertools解决无序排列组合问题

将零移到最后:为啥我的 Python 代码未能通过 CodeWars 中的测试?

它们是“相同”的 CodeWars。我的代码没有通过所有测试

codewars另一个可以锻炼代码编程能力的网站

codewars另一个可以锻炼代码编程能力的网站

错误记录Android Studio 编译报错 ( Could not determine java version from ‘11.0.8‘. | Android Studio 降级 )(代码片段