Sam and substrings Discussions | Algorithms | HackerRank
  • + 0 comments

    JAVA SOLUTION

     private final static BigInteger MOD = BigInteger.valueOf(1000000007);
    
        /*
         * Input: 123456 
         * Role of '2': 2, 20, 200, 2000, 20000, 200000
         */
        public static int substrings(String number) {
            int length = number.length();
            BigInteger totalSum = BigInteger.valueOf(0);
            BigInteger multiplier = BigInteger.valueOf(1);
            BigInteger sum = BigInteger.valueOf(0);
    
            // Iterate over each digit from the end to the start
            for (int i = length - 1; i >= 0; i--) {
                BigInteger digit = BigInteger.valueOf(Character.getNumericValue(number.charAt(i)));
                sum = (sum.add(digit.multiply(multiplier))).mod(MOD);
                totalSum = (totalSum.add(sum)).mod(MOD);
                multiplier = (multiplier.multiply(BigInteger.valueOf(10)).add(BigInteger.valueOf(1))).mod(MOD);
            }
    
            return totalSum.intValue();
        }