Hello everyone,
In
this tutorial, we will see how we can convert an integer into an array of
integers. First, what does that mean? What we mean is that the program will
accept an integer number such as "76342986" and will convert it into
an array of integers
7
|
6
|
3
|
4
|
2
|
9
|
8
|
6
|
so
you can deal with any digit individually.
Why
is that even useful?
Converting
a whole integer into an array of integers can be useful in many ways:
·
Stem-and-leaf calculation
·
To create the largest
possible number from a given number
·
Working on place values
·
Finding significant figures
·
You can write an
application to convert numbers to corresponding strings
·
You can check divisibility
of a number
·
To be able to express a
number in extended form
and
there are plenty other applications (in particular, math applications) where
you will need to deal with the digits individually.
So, how do we do that?
Here
are the steps we're going to follow:
1-
Accept the number as string
2-
Convert the string-number
into an array of characters
3-
Declare an array of
integers that have the same length as the array of characters
4-
Apply the equation:
Array_of_numbers[] = array_of_characters[] –
'0';
Which will return the number and will be
stored in the array of integers.
E.g.,
If the first number in the array of
characters is 7, then
Array_of_numbers[0] = array_of_characters[0]
– '0';
// Array_of_numbers[0] = '7' – '0';
// Array_of_numbers[0] = 7;
And
so on.
A question may pop up: how it works? Actually when we subtract characters here, we basically subtract ASCII values. So the ASCII value of 5 is 53 and for 0 is 48, so 53 – 48 = 5, and this similar to the numbers from 0 to 9.
what if the user entered a negative number?
If the user entered a negative number say -12332, then this
will be the array_of_characters[]
-
|
1
|
2
|
3
|
3
|
2
|
So how do we handle such situation?
- After converting the whole number to an array_of_characters[], we check the first location whether it has a negation sign or not
- If it has the negation sign, then re-initialize the size of the Array_of_numbers to be array_of_characters.Length -1. And this is because the additional one space that the negation sign takes
- We start converting the array_of_characters[] to Array_of_numbers[] from the second location of array_of_characters[]
- To here, the Array_of_numbers[] will be:
1
|
2
|
3
|
3
|
2
|
- Lastly, make the first number in the array negative:
To make sure that the code is correct, we add a sum
variable to sum all the numbers and check the result whether it is correct or
not.
Note: If you have a better way to solve the problem or to optimize
the code, please feel free to comment it down. I will be happy to see your
contribution.
Here is the full Csharp code:
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Collections.ObjectModel; namespace TestConsole { class Program { static void Main(string[] args) { Console.WriteLine("Enter a number"); string stringNumber = Console.ReadLine(); char[] charnumbers = stringNumber.ToCharArray(); int[] theNumbers = new int[charnumbers.Length]; bool negativeNumber = false; int sum = 0; if (charnumbers[0] == '-') { negativeNumber = true; theNumbers = new int[charnumbers.Length - 1]; } for (int i = 0; i < theNumbers.Length; i++) { if (negativeNumber == true) theNumbers[i] = charnumbers[i + 1] - '0'; else theNumbers[i] = charnumbers[i] - '0'; } if (negativeNumber == true) theNumbers[0] = -theNumbers[0]; Console.WriteLine("the number is {0} digits", theNumbers.Length); for (int i = 0; i < theNumbers.Length; i++) { Console.WriteLine("[{0}] => {1}", i, theNumbers[i]); sum += theNumbers[i]; } Console.WriteLine("The sum is {0}", sum); Console.ReadLine(); } } }
Why so much code? You're doing it the hard way! You can achieve the same thing (and more efficiently) with just a few lines of code:
ReplyDeleteint num = -234556;
var numArray = new List(Math.Abs(num).ToString().ToCharArray().Select(i => int.Parse(i.ToString())));
if (num < 0) numArray[0] *= -1;
var sum = numArray.Sum();
Less code != better code
ReplyDeleteideally you should avoid converting back and forth from int to string. I'd implement this as an extension method, as such:
namespace System
{
public static class Int32Extensions
{
public static int[] ToArray(this int input)
{
var sign = 1;
return input.ToArray(out sign);
}
public static int[] ToArray(this int input, out int multiplier)
{
multiplier = input > 0 ? 1 : input == 0 ? 0 : -1;
if (input == 0)
{
return new int[] { 0 };
}
input = Math.Abs(input);
var list = new List();
for (var i = 1000000000; i > 0; i /= 10)
{
if (i > input)
{
continue;
}
list.Add((input / i) % 10);
}
return list.ToArray();
}
}
}
Usage:
const int number = 76342986; // simulated input
var sign = 1;
var list = number.ToArray();
//or
var list2 = number.ToArray(out sign);
//use "sign" to track positive or negative number.