This question already has answers here:
Is there an easy way to turn an int into an array of ints of each digit?
(11 answers)
Closed 7 years ago.
I want to know if there is a way in C# to convert an integer to an array of digits so that I can perform (Mathematical) operations on each digit alone.
Example: I need the user to input an integer i.e 123, 456
then the program creates two arrays of three elements {1,2,3}, {4,5,6}.
Off the top of my head:
int i = 123;
var digits = i.ToString().Select(t=>int.Parse(t.ToString())).ToArray();
You could create such array (or List) avoiding string operations as follows:
int x = 123;
List<int> digits = new List<int>();
while(x > 0)
{
int digit;
x = Math.DivRem(x, 10, out digit);
digits.Add(digit);
}
digits.Reverse();
Alternative without using the List and the List.Reverse:
int x = 456;
int[] digits = new int[1 + (int)Math.Log10(x)];
for (int i = digits.Length - 1; i >= 0; i--)
{
int digit;
x = Math.DivRem(x, 10, out digit);
digits[i] = digit;
}
And one more way using ToString:
int x = 123;
int[] digits = Array.ConvertAll(x.ToString("0").ToCharArray(), ch => ch - '0');
You can use this and not convert to a string:
var digits = new List<int>();
var integer = 123456;
while (integer > 0)
{
digits.Add(integer % 10);
integer /= 10;
}
digits.Reverse();
Related
I'm looking for a way to replace every int that is greater than 9 in an array with the sum of the digits. I'm gonna demonstrate an example below.
I have this array:
int[] ints2 = new int[] { ints[0] * 2, ints[1], ints[2] * 2, ints[3], ints[4] * 2, ints[5], ints[6] * 2, ints[7], ints[8] * 2, ints[9]};
And I want to replace the first int to whatever the sum is of the two digits.
Lets say ints[0] = 9. And ints[0]*2 = 18. The sum should be 1+8 = 9.
Can I use some kind of replace method for ints? Or do you guys have any better ideas of how to deal with this issue?
I tried it like this, but obviously I'm wrong:
foreach (int number in ints)
{
int newNumberInt;
if (number > 9)
{
string newNum = number.ToString();
char[] charNum = newNum.ToCharArray();
int[] intNum = Array.ConvertAll(charNum, n => (int)Char.GetNumericValue(n));
newNumberInt = intNum[0] + intNum[1];
}
newNumberInt = number;
}
You are close. Your mistakes are an incorrect addition of digits, and failure to replace the values in the array. Here is a one line method that adds all the digits in an integer (using System.Linq):
//Adds up all the digits in a number
private static int AddDigits(int number) => number.ToString().Sum(digitCharacter => int.Parse(digitCharacter.ToString()));
For replacing the values, a foreach loop directly on the array won't work, due to changing the contents of the array during enumeration. A simple solution is to use a for loop.
for (int i = 0; i < ints.Length; i++)
{
var value = ints[i];
ints[i] = value > 9 ? AddDigits(value) : value;
}
Note: the AddDigits function I wrote only works for positive integers
I have an int variable (value1).
Int value1 =95478;
I want to take each digit of value1 and insert them into an array (array1). Like this,
int[] array1 = { 9, 5, 4, 7, 8 };
No idea how this can be done. Any idea?
int[] array1 = 95478.ToString()
.Select(x => int.Parse(x.ToString()))
.ToArray();
try this
Int value1 =95478;
List<int> listInts = new List<int>();
while(value1 > 0)
{
listInts.Add(value1 % 10);
value1 = value1 / 10;
}
listInts.Reverse();
var result= listInts .ToArray();
this doesn't use strings
The most optimal solution I could come up with:
public static class Extensions {
public static int[] SplitByDigits(this int value) {
value = Math.Abs(value); // undefined behaviour for negative values, lets just skip them
// Initialize array of correct length
var intArr = new int[(int)Math.Log10(value) + 1];
for (int p = intArr.Length - 1; p >= 0; p--)
{
// Fill the array backwards with "last" digit
intArr[p] = value % 10;
// Go to "next" digit
value /= 10;
}
return intArr;
}
}
Is roughly double the speed of using a List<int> and reversing, roughly ten times faster and a tonne more memory efficient than using strings.
Just because you have a powerful computer you are not allowed to write bad code :)
I want to make a method that takes a variable of type int or long and returns an array of ints or longs, with each array item being a group of 3 digits. For example:
int[] i = splitNumber(100000);
// Outputs { 100, 000 }
int[] j = splitNumber(12345);
// Outputs { 12, 345 }
int[] k = splitNumber(12345678);
// Outputs { 12, 345, 678 }
// Et cetera
I know how to get the last n digits of a number using the modulo operator, but I have no idea how to get the first n digits, which is the only way to make this method that I can think of. Help please!
Without converting to string:
int[] splitNumber(int value)
{
Stack<int> q = new Stack<int>();
do
{
q.Push(value%1000);
value /= 1000;
} while (value>0);
return q.ToArray();
}
This is simple integer arithmetic; first take the modulo to get the right-most decimals, then divide to throw away the decimals you already added. I used the Stack to avoid reversing a list.
Edit: Using log to get the length was suggested in the comments. It could make for slightly shorter code, but in my opinion it is not better code, because the intent is less clear when reading it. Also, it might be less performant due to the extra Math function calls. Anyways; here it is:
int[] splitNumber(int value)
{
int length = (int) (1 + Math.Log(value, 1000));
var result = from n in Enumerable.Range(1,length)
select ((int)(value / Math.Pow(1000,length-n))) % 1000;
return result.ToArray();
}
By converting into a string and then into int array
int number = 1000000;
string parts = number.ToString("N0", new NumberFormatInfo()
{
NumberGroupSizes = new[] { 3 },
NumberGroupSeparator = "."
});
By using Maths,
public static int[] splitNumberIntoGroupOfDigits(int number)
{
var numberOfDigits = Math.Floor(Math.Log10(number) + 1); // compute number of digits
var intArray = new int[Convert.ToInt32(numberOfDigits / 3)]; // we know the size of array
var lastIndex = intArray.Length -1; // start filling array from the end
while (number != 0)
{
var lastSet = number % 1000;
number = number / 1000;
if (lastSet == 0)
{
intArray[lastIndex] = 0; // set of zeros
--lastIndex;
}
else if (number == 0)
{
intArray[lastIndex] = lastSet; // this could be your last set
--lastIndex;
}
else
{
intArray[lastIndex] = lastSet;
--lastIndex;
}
}
return intArray;
}
Try converting it to string first and do the parsing then convert it back to number again
Convert to string
Get length
If length modulus 3 == 0
String substring it into ints every 3
else if
Find remainder such as one or two left over
Substring remainder off of front of string
Then substring by 3 for the rest
You can first find out how large the number is, then use division to get the first digits, and modulo to keep the rest:
int number = 12345678;
int len = 1;
int div = 1;
while (number >= div * 1000) {
len++;
div *= 1000;
}
int[] result = new int[len];
for (int i = 0; i < result.Length; i++) {
result[i] = number / div;
number %= div;
div /= 1000;
}
You can use this with the System.Linq namespace from .NET 3.5 and above:
int[] splitNumber(long value)
{
LinkedList<int> results = new LinkedList<int>();
do
{
int current = (int) (value % 1000);
results.AddFirst(current);
value /= 1000;
} while (value > 0);
return results.ToArray();// Extension method
}
I use LinkedList<int> to avoid having to Reverse a list before returning. You could also use Stack<int> for the same purpose, which would only require .NET 2.0:
int[] splitNumber(long value)
{
Stack<int> results = new Stack<int>();
do
{
int current = (int) (value % 1000);
results.Push(current);
value /= 1000;
} while (value > 0);
return results.ToArray();
}
I have a number something like this :
12345668788451223356456898941220036696897894
Now, the question is how can I split the number after each 8 digits.That is,
I need the output as :
12345668
78845122 and so on up to the end of the number.
If I convert it to string, I don't have a method so that I could split it only with length parameter.
Thanks in advance for answering.
String approach
If I convert it to string, I don't have a method so that I could split it only with length parameter.
Well you have Substring, don't you? You could use LINQ:
var numbers = Enumerable.Range(0, bigNumber.Length / 8)
.Select(x => bigNumber.Substring(x * 8, 8)
.ToList();
or a straight loop:
var numbers = new List<string>();
for (int i = 0; i < bigNumber.Length / 8; i++)
{
numbers.Add(bigNumber.Substring(i * 8, 8);
}
If you need to end up with a List<int> instead, just add a call to int.Parse in there.
(You should check that the input string length is a multiple of 8 first.)
BigInteger approach
It's not clear what form you have this number in to start with. If it's a BigInteger, you could keep using DivRem:
BigInteger value = ...;
List<BigInteger> results = new List<BigInteger>();
BigInteger divisor = 100000000L;
for (int i = 0; i < count; i++)
{
BigInteger tmp;
value = BigInteger.DivRem(value, divisor, out tmp);
results.Add(tmp);
}
Note that I'm using count here rather than just looping until value is 0, in case you have lots of leading 0s. You need to know how many numbers you're trying to extract :)
Use this regex to split after each 8 digits,
\d{1,8}
OR
(\d{1,8})
Output:
12345668
78845122
33564568
98941220
03669689
7894
Have you tried using
string string.substring(int startIndex,int length)
In you case, you can write a loop to extract the 8 digits from the string till all the numbers are extracted
string sDigits = "12345668788451223356456898941220036696897894";
int iArrLen = sDigits.length / 8;
string[] sArrDigitList = new string[iArrLen];
for(int i=0; i < sDigits.length; i++)
{
sArrDigitList[i] = sDigits.substring(0, 8);
sDigits = sDigits.substring(sDigits.length-8);
}
I need to create a modulus check which adds leading digits, lets say 0, to a seed int. I then need to return an array of digits in the array as I need to do a calculation on each digit to return a new whole number.
my code is as follows,
var seed = 1234;
var seedString = seed.ToString();
var test = new List<int>();
for(int i = 0; i < 10 - seedString.Length; i++)
{
test.Add(0);
}
var value = seed;
for(int i = 0; i < seedString.Length; i ++)
{
test.Insert(10 - seedString.Length, value % 10);
value = value / 10;
}
is there an easier way of doing this?
If you want to convert your number to a 10-digit string, you can format the number using a Custom Numeric Format String as follows:
string result = seed.ToString("0000000000");
// result == "0000001234"
See: The "0" Custom Specifier
If you need a 10-element array consisting of the individual digits, try this:
int[] result = new int[10];
for (int value = seed, i = result.Length; value != 0; value /= 10)
{
result[--i] = value % 10;
}
// result == new int[] { 0, 0, 0, 0, 0, 0, 1, 2, 3, 4 }
See also: Fastest way to separate the digits of an int into an array in .NET?
Try this:
int myNumber = 1234;
string myStringNumber = myNumber.ToString().PadLeft(10, '0');
HTH
Another shorthand way of getting the string representation would be
int num = 1234;
num.ToString("D10");