Given a number as a string , find the number of contiguous subsequences which recursively add up to 9 | Set 2 | Javascript program to count substrings with recursive sum equal to 9 ; to store no . of previous encountered modular sums ; no . of modular sum ( == 0 ) encountered till now = 1 ; if number is 0 increase ; no . of continuous_zero by 1 ; else continuous_zero is 0 ; increase d value of this mod_sum ; subtract no . of cases where there are only zeroes in substring ; driver program to test above function
function count9s ( number ) { let n = number . length ; let d = new Array ( 9 ) ; for ( let i = 0 ; i < d . length ; i ++ ) { d [ i ] = 0 ; } d [ 0 ] = 1 ; let result = 0 ; let mod_sum = 0 , continuous_zero = 0 ; for ( let i = 0 ; i < n ; i ++ ) { if ( ( number [ i ] - ' ' ) == 0 ) { continuous_zero ++ ; } else { continuous_zero = 0 ; } mod_sum += ( number [ i ] - ' ' ) ; mod_sum %= 9 ; result += d [ mod_sum ] ; d [ mod_sum ] ++ ; result -= continuous_zero ; } return result ; } document . write ( count9s ( " " ) + " " ) ; document . write ( count9s ( " " ) + " " ) ; document . write ( count9s ( " " ) + " " ) ;