how do I split up a four digit number in java and sum up the individual numbers to get their sum?
-reply by willie
| |
|
Welcome to AstaHost - Dear Guest | |
Posted 28 September 2010 - 07:44 AM
how do I split up a four digit number in java and sum up the individual numbers to get their sum?
-reply by willie
Posted 03 January 2006 - 04:04 AM
Posted 03 January 2006 - 03:28 AM
Posted 30 December 2005 - 07:21 AM
Posted 30 December 2005 - 07:03 AM
Posted 30 December 2005 - 03:48 AM
'Say my number is stored in a variable called Num Dim Num As Integer = 54321 'First I declare two variables - actually one Array to hold each character 'We just assing a random number of elements to the array - having 32 'will help us deal with numbers as long as 32 digits long Dim Digits (32) As Integer 'And one variable to hold the length of the string Dim Length As Integer 'I convert it to a String first Dim NumString As String = CType ( Num, String ) 'This NULL-Check is implemented so that if you use an empty string here, the code 'won't crash when it comes to checking for the substring - but instead would 'gracefully skip this part altogether If NumString <> "" Then 'Now I find the length of the string - Length = NumString.Length 'Iterate through the string, picking up each character For Index As Integer = 0 To Length - 1 Digits ( Index ) = CType ( NumString.SubString ( Index, 1 ), Integer ) Next End If
'Say Num contains the number Dim Num As Integer = 54321 'Once again - we find the length of the number - which gives us the number of 'digits in it, and then we declare an array based on that number Dim Length As Integer If Str ( Num ) <> "" Then Length = Str ( Num ).Length End If 'Next we declare two variables and an array Dim Divisor As Integer = 10 ^ ( Length - 1 ) Dim Index As Integer = 0 Dim Digits ( Length - 1 ) As Integer 'Here we start the Loop While ( Divisor > 0 ) 'Extract the first digit Digits ( Index ) = Int ( Num / Divisor ) 'Extract remainder number - and store it back in Num Num = Num Mod Divisor 'Decrease Divisor's value by 1/10th units Divisor /= 10 'Increment Index Index += 1 End While
Posted 29 December 2005 - 10:58 PM
Community Forum Software by IP.Board
Licensed to: Xisto Corporation

