split int value into separate digits
List<Integer> digits(int i) {
List<Integer> digits = new ArrayList<Integer>();
while(i > 0) {
digits.add(i % 10);
i /= 10;
}
return digits;
}
How do I split an int into its digits?
Given the number 12345 :
5
is 12345 % 10
4
is 12345 / 10 % 10
3
is 12345 / 100 % 10
2
is 12345 / 1000 % 10
1
is 12345 / 10000 % 10
I won't provide a complete code as this surely looks like homework, but I'm sure you get the pattern.
How to split an Int to its individual digits?
We can also extend the StringProtocol and create a computed property:
edit/update: Xcode 11.5 • Swift 5.2
extension StringProtocol {
var digits: [Int] { compactMap(\.wholeNumberValue) }
}
let string = "123456"
let digits = string.digits // [1, 2, 3, 4, 5, 6]
extension LosslessStringConvertible {
var string: String { .init(self) }
}
extension Numeric where Self: LosslessStringConvertible {
var digits: [Int] { string.digits }
}
let integer = 123
let integerDigits = integer.digits // [1, 2, 3]
let double = 12.34
let doubleDigits = double.digits // // [1, 2, 3, 4]
In Swift 5 now we can use the new Character
property wholeNumberValue
let string = "123456"
let digits = string.compactMap{ $0.wholeNumberValue } // [1, 2, 3, 4, 5, 6]
Get separate digits from int in C#
I came up with an individual puzzled out solution.
#1: Own created solution
public static IEnumerable<int> GetDigits(int source)
{
int individualFactor = 0;
int tennerFactor = Convert.ToInt32(Math.Pow(10, source.ToString().Length));
do
{
source -= tennerFactor * individualFactor;
tennerFactor /= 10;
individualFactor = source / tennerFactor;
yield return individualFactor;
} while (tennerFactor > 1);
}
#2: Modulo with Linq's .Reverse()
After that I explored the Internet for other solutions and I came across one from the Java folks: How to get the separate digits of an int number?
The downside is that the order of integers in the collection is reversed. Here comes Microsoft's Linq.
How to call the method with .Reverse()
.
...
GetDigits2(input).Reverse()
...
And the actual method.
public static IEnumerable<int> GetDigits2(int source)
{
while (source > 0)
{
var digit = source % 10;
source /= 10;
yield return digit;
}
}
#3: Modulo with Stack's LIFO
What else could I do when I do not want to think about calling .Revers()
after the method (GetDigits2(int source)
)? So I use a variable inside the method, call .Reverse() on the variable and return its result instead.
Or something totally different: I remember the LIFO logic. In .NET you use the Stack class for that.
public static IEnumerable<int> GetDigits3(int source)
{
Stack<int> digits = new Stack<int>();
while (source > 0)
{
var digit = source % 10;
source /= 10;
digits.Push(digit);
}
return digits;
}
Testing
I tested each method 10 million times and measured the number of tickes between start and end of the test.
#1: Own Created method
1'549'084 ticks
#2: Modulo with Linq's .Reverse()
2'252'875 ticks
#3: Modulo with Stack's LIFO
23'626'839 ticks
tl;dr
Here comes the fiddle: Get Digits from int
Extracting each digit in an int
The "hint" is actually a nearly direct explanation of how to do what you need to do: dividing in integers by ten gets rid of the last digit, while obtaining modulo ten gives you the last digit:
int x = 12345;
int lastDigit = x % 10; // This is 5
int remainingNumber = x / 10; // This is 1234
Do this in a loop until the remaining number is zero. This gives you digits of the number in reverse.
JavaScript Number Split into individual digits
var number = 12354987,
output = [],
sNumber = number.toString();
for (var i = 0, len = sNumber.length; i < len; i += 1) {
output.push(+sNumber.charAt(i));
}
console.log(output);
/* Outputs:
*
* [1, 2, 3, 5, 4, 9, 8, 7]
*/
UPDATE: Calculating a sum
for (var i = 0, sum = 0; i < output.length; sum += output[i++]);
console.log(sum);
/*
* Outputs: 39
*/
Related Topics
How to Find All Subclasses of a Given Class in Java
Why Does Java Have Transient Fields
How to Programmatically Determine Operating System in Java
How to Extract Numbers from a String and Get an Array of Ints
Try/Catch With Inputmismatchexception Creates Infinite Loop
Is It Safe to Use a Static Java.Sql.Connection Instance in a Multithreaded System
Understanding Spring @Autowired Usage
Java: Date from Unix Timestamp
How Does a Preparedstatement Avoid or Prevent SQL Injection
Is There an Advantage to Use a Synchronized Method Instead of a Synchronized Block
Are Static Methods Inherited in Java
How to Read a File from Jar in Java
Get the Height of a Node in Javafx (Generate a Layout Pass)
How to Assert That a Certain Exception Is Thrown in Junit Tests