当前位置: 代码迷 >> 综合 >> exercism————Luhn
  详细解决方案

exercism————Luhn

热度:24   发布时间:2023-12-13 18:10:57.0

题目:

在这里插入图片描述

解法一:

boolean isVlaid(String s) {
    String number = s.replaceAll(" ","");// check the argumentif (number.length() <= 1 || number.matches("[^0-9]")) {
    throw new IllegalArgumentException("Invalid Argument");}// Converse char to intchar[] set = number.toCharArray();int[] num = new int[set.length];for (int i = 0; i < set.length; i++) {
    num[i] = Character.getNumericValue(set[i]);}// calculate double of every two digitfor (int i = set.length - 2; i >= 0; i -= 2) {
    if (2 * num[i] > 9) {
    num[i] = 2 * num[i] - 9;}else {
    num[i] = 2 * num[i];}}// add all the digitsint sum = 0;for (int i = 0; i < num.length; i++) {
    sum += num[i];}return sum % 10 == 0;}

解法二:

 boolean isValid(String candidate) {
    int[] digits = new StringBuilder(candidate).reverse().toString().replace(" ", "").chars().map(Character::getNumericValue).toArray();if (digits.length < 2){
    return false;}if (Arrays.stream(digits).anyMatch(LuhnValidator::isInvalid)){
    return false;}int sum = IntStream.range(0, digits.length).map(i -> calculateDigitValue(digits[i], i)).sum();return sum % 10 == 0;}private static boolean isInvalid(Integer digit){
    return digit < 0 || digit > 9;}private static Integer calculateDigitValue(Integer digit, Integer index){
    if (index % 2 == 0){
    return digit;}int digitDoubled = digit << 1;if (digitDoubled >= 10){
    return digitDoubled - 9;}return digitDoubled;}

解法三:

public boolean isValid(String str) {
    String s = str.replaceAll(" ", "");String[] nums = s.split("");return s.matches("^\\d{2,}") && getSum(nums) % 10 == 0;}private int getSum(String[] nums) {
    // 如果nums.length为偶数,则从下标0开始,如果nums.length为奇数,则从下标1开始int startDigit = (nums.length & 1) == 0 ? 0 : 1;// 如果为偶数位,则加倍偶数下标;如果位奇数,则加倍奇数下标return IntStream.range(0, nums.length).map(i -> (i & 1) == startDigit ? doubleDigit(Integer.parseInt(nums[i])) : Integer.parseInt(nums[i])).sum();}private int doubleDigit(int x) {
    if (x * 2 > 9) {
    return x * 2 - 9;};return x * 2;}

总结:

  • 解法一:中规中矩,正常思路
  • 解法二:条理清晰,可读性较强
  • 解法三:解法惊奇,找到偶数和奇数长度时,加倍下标也是偶数和奇数,所以只要加倍对应的下标数就ok了,妙!