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]
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 integer into individual digits and then square each number?
Your code isn't working because you don't actually use the return value of Math.pow()
.
Math.pow(x, 2)
is one way to raise a number to the power of 2, but it is floating-point math, not integer math. Power of 2 means to multiply the number by itself, so x * x
is much better.
int number = 299792458; // Speed of light in m/s
for (char ch : Integer.toString(number).toCharArray()) {
int digit = ch - '0';
System.out.println(digit * digit);
}
Or using Java 8 streams:
int number = 299792458; // Speed of light in m/s
Integer.toString(number)
.chars()
.map(c -> (c - '0') * (c - '0'))
.forEach(System.out::println);
OUTPUT
4
81
81
49
81
4
16
25
64
How do I split an integer into individual digits?
But the borrow checker says the string doesn't live long enough.
That's because it doesn't. You aren't using the iterator, so the type of digits
is
std::iter::Map<std::str::Chars<'_>, <closure>>
That is, a yet-to-be-evaluated iterator that contains references to the allocated string (the unnamed lifetime '_
in Chars
). However, since that string has no owner, it is dropped at the end of the statement; before the iterator is consumed.
So, yay for Rust, it prevented a use-after-free bug!
Consuming the iterator would "solve" the problem, as the references to the allocated string would not attempt to live longer than the allocated string; they all end at the end of the statement:
let digits: Vec<_> = num.to_string().chars().map(|d| d.to_digit(10).unwrap()).collect();
If you wanted to return an iterator, you can then convert the Vec
back into an iterator:
fn digits(num: usize) -> impl Iterator<Item = u32> {
num.to_string()
.chars()
.map(|d| d.to_digit(10).unwrap())
.collect::<Vec<_>>()
.into_iter()
}
As for an alternate solution, there's the math way, stolen from the C++ question to create a vector:
fn x(n: usize) -> Vec<usize> {
fn x_inner(n: usize, xs: &mut Vec<usize>) {
if n >= 10 {
x_inner(n / 10, xs);
}
xs.push(n % 10);
}
let mut xs = Vec::new();
x_inner(n, &mut xs);
xs
}
fn main() {
let num = 42;
let digits: Vec<_> = num.to_string().chars().map(|d| d.to_digit(10).unwrap()).collect();
println!("{:?}", digits);
let digits = x(42);
println!("{:?}", digits);
}
However, you might want to add all the special case logic for negative numbers, and testing wouldn't be a bad idea.
You might also want a fancy-pants iterator version:
fn digits(mut num: usize) -> impl Iterator<Item = usize> {
let mut divisor = 1;
while num >= divisor * 10 {
divisor *= 10;
}
std::iter::from_fn(move || {
if divisor == 0 {
None
} else {
let v = num / divisor;
num %= divisor;
divisor /= 10;
Some(v)
}
})
}
Or the completely custom type:
struct Digits {
n: usize,
divisor: usize,
}
impl Digits {
fn new(n: usize) -> Self {
let mut divisor = 1;
while n >= divisor * 10 {
divisor *= 10;
}
Digits {
n: n,
divisor: divisor,
}
}
}
impl Iterator for Digits {
type Item = usize;
fn next(&mut self) -> Option<Self::Item> {
if self.divisor == 0 {
None
} else {
let v = Some(self.n / self.divisor);
self.n %= self.divisor;
self.divisor /= 10;
v
}
}
}
fn main() {
let digits: Vec<_> = Digits::new(42).collect();
println!("{:?}", digits);
}
See also:
- What is the correct way to return an Iterator (or any other trait)?
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
*/
How do I separate an integer into separate digits in an array in JavaScript?
Why not just do this?
var n = 123456789;
var digits = (""+n).split("");
i want to split the integer into individual elements and add the elements
You can also do this:
number = int(input("Enter the Number: "))
sum_of_digits = 0
while number > 0:
digit = number % 10
sum_of_digits = sum_of_digits + digit
number = number // 10
Related Topics
In Swift, Can You Split a String by Another String, Not Just a Character
Contextual Type for Closure Argument List Expects 1 Argument, But 4 Were Specified
Create Nsmanagedobject Subclass... Make a New Error in My Project
iOS Facebook Sdk: Login Doesn't Return Email Despite Permissions Granted
Swift 4 Decode Simple Root Level JSON Value
Swiftui List Empty State View/Modifier
Can't Hook Up an Outlet Collection in Xcode 6 Using Storyboard
Constant Speed Orbit Around Point with Sknode
Swift, Auto Resize Custom Table View Cells
Why Should Not Directly Extend Uiview or Uiviewcontroller
Swift - Avaudioplayer, Sound Doesn't Play Correctly
Arkit - Viewport Size VS Real Screen Resolution
Swift Error Handling for Methods That Do Not Throw
Mutable Binding in Swiftui Live Preview
How to Drag and Drop a Sprite in Swift 3.0
Convert String to Bool in Swift - via API or Most Swift-Like Approach