标签:value mil 题目 循环 man solution use 数字密码 sim
无意中发现一个代码题目的网站,做了一个题,深有感触。记下来大牛们的解决思路
渣渣程序员就是我了,我会先列自己的写法,再列大牛的写法,共勉。
题目:传入一个数字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; }
标签:value mil 题目 循环 man solution use 数字密码 sim
原文地址:https://www.cnblogs.com/liangwen/p/12019306.html