Sum of Digits / Digital Root

kata programming

مساله:

عبارت Digital root به معنی حالت برگشتی جمع تمام رقم های یک عدد است تا زمانی که حاصل جمع برابر یک رقم شود.

به شما عدد n داده می شود و شما باید حاصل جمع رقم های آن را بدست بیاورید. اگر نتیجه عددی با بیش از یک رقم شود باید این کار را تکرار کنید تا زمانی که حاصل جمع برابر یک رقم شود. ورودی به صورت مثبت می باشد.

مثال ها:

16  -->  1 + 6 = 7
   942  -->  9 + 4 + 2 = 15  -->  1 + 5 = 6
132189  -->  1 + 3 + 2 + 1 + 8 + 9 = 24  -->  2 + 4 = 6
493193  -->  4 + 9 + 3 + 1 + 9 + 3 = 29  -->  2 + 9 = 11  -->  1 + 1 = 2

Description:

Digital root is the recursive sum of all the digits in a number.

Given n, take the sum of the digits of n. If that value has more than one digit, continue reducing in this way until a single-digit number is produced. The input will be a non-negative integer.

Examples

    16  -->  1 + 6 = 7
   942  -->  9 + 4 + 2 = 15  -->  1 + 5 = 6
132189  -->  1 + 3 + 2 + 1 + 8 + 9 = 24  -->  2 + 4 = 6
493193  -->  4 + 9 + 3 + 1 + 9 + 3 = 29  -->  2 + 9 = 11  -->  1 + 1 = 2

راه حل ها:

public class DRoot {
  public static int digital_root(int n) {
    return (n != 0 && n%9 == 0) ? 9 : n % 9;
  }
}
public class DRoot {
  public static int digital_root(int n) {
    while(n > 9){
      n = n/10 + n % 10;
      }
    return(n);
  }
}
public class DRoot {
  public static int digital_root(int n) {
    return n < 10 ? n : digital_root(digital_root(n/10)+n%10);
  }
}
public class DRoot {
  public static int digital_root(int n) {
    return (1 + (n - 1) % 9);
  }
}
public class DRoot {
  public static int digital_root(int n) {
  
    if (String.valueOf(n).length() > 1) {
      int digitSum = 0;
      String numAsString = String.valueOf(n);
      
      for (int i = 0; i < numAsString.length(); i++) {
        int digit = Character.getNumericValue(numAsString.charAt(i));
        digitSum += digit;
      }
      return digital_root(digitSum);
    }
    
    else  {
      return n;
    }  
  }
}
public class DRoot {
  public static int digital_root(int n) {
    return --n % 9 + 1;
  }
}
public class DRoot {
  public static int digital_root(int n) {
    final int result = String.valueOf(n).chars().reduce(0, (acc, curr) -> acc + (curr - '0'));
    return result < 10 ? result : digital_root(result);
  }
}
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class DRoot {
  public static int digital_root(int n) {
    do {
      n = (int) Stream.of(String.valueOf(n).split("")).collect(Collectors.summarizingInt(Integer::parseInt)).getSum();
    } while (Math.abs(n) > 9);
    return n;
  }
}

دیدگاهتان را بنویسید