Home > Software design >  sum digits of a numbers until get one-digit number
sum digits of a numbers until get one-digit number

Time:11-13

this code works, if it is for example i have a number 14, it will give 1 4=5 but if I have, for example, 78, the result will be 7 8=15and I expect to display 1 5=6,so it will be 6, not 15. so how do I solve this?

   Dim lines As String() = originalString.Split(CChar(Environment.NewLine))

            For Each line As String In lines

                Dim lineSum As String = Nothing

                For Each numberChar As Char In line
                    If Asc(numberChar) >= 48 AndAlso Asc(numberChar) < 58 Then  'making sure this is a number and nothing else
                        lineSum  = Asc(numberChar) - 48 'using the ascii chart to determine the value tu add
                    End If
                Next

                If results <> "" Then results &= vbNewLine
                results &= lineSum.ToString

            Next

CodePudding user response:

You can use this recursive method:

Public Shared Function GetSum(number As String, Optional maxDigits As Int32? = Nothing) As Int32?
    If Not number.All(AddressOf Char.IsDigit) Then Return Nothing
    Dim sum = number.Sum(AddressOf Char.GetNumericValue)
    If(Not maxDigits.HasValue Orelse sum.ToString().Length <= maxDigits) Then Return sum
    Return GetSum(sum.ToString(), maxDigits)
End Function

With your sample:

Sub Main
    Dim sum1 As Int32? = GetSum("14", 1)
    Dim sum2 As Int32? = GetSum("78", 1)
    Console.WriteLine("Sum of 14: " & sum1)
    Console.WriteLine("Sum of 78: " & sum2)
End Sub

Output:

Sum of 14: 5
Sum of 78: 6
  • Related