I tried to make a function that would subtract from a number, for example number 25, to display the result 3 (because 5-2=3) – the smallest is subtracted from the large number – while the numbers from 1 to 9 will remain the same so it will take into account only what is of 2 digits. unfortunately I kind of failed in my attempt and I would need a little help.
Dim lines As String() = originalString.Split(CChar(Environment.NewLine))
For Each line As String In lines
Dim lineSum As String = 0
Dim index As Integer = 0
Dim numchars1 As Char
Dim numchars2 As Char
For Each numberChar As Char In line
index += 1
If index = 1 Then
numchars1 = numberChar
End If
If index >= 2 Then
numchars2 = numberChar
End If
Next
If Val(numchars1) AndAlso Val(numchars2) > 0 Then
If Val(numchars2) > Val(numchars1) Then
lineSum = Val(numchars2) - Val(numchars1)
ElseIf Val(numchars1) > Val(numchars2) Then
lineSum = Val(numchars1) - Val(numchars2)
End If
Else
lineSum = numchars1
End If
>Solution :
You can use this approach:
Public Shared Function Subtract(number As String) As Int32?
If Not number.All(AddressOf Char.IsDigit) Then Return Nothing
Dim allNumbers As Int32() = number.Select(Function(c) CInt(Char.GetNumericValue(c))).ToArray()
Dim highest = allNumbers.Max()
Return highest - (allNumbers.Sum() - highest)
End Function
Note that the result of "555" will be -5, because 5 – 5 – 5