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]
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
Split an Integer into its digits c++
Your problem comes from the fact that you are reading the digits backwards, thus you need to print them out backwards. A stack will help you tremendously.
#include "stdafx.h"
#include <cstdlib>
#include <iostream>
#include <math.h>
#include <stack>
int countDigitsInInteger(int n)
{
int count =0;
while(n>0)
{
count++;
n=n/10;
}
return count;
}
using namespace std;
int main(int argc, char *argv[])
{
int intLength =0;
int number;
int digit;
int sum = 0;
string s;
cout << "Please enter an integer ";
cin >>number;
cout << "Orginal Number = "<<number <<endl;
//make the number positive
if (number<0)
number = -number;
intLength = countDigitsInInteger(number);
//break apart the integer into digits
stack<int> digitstack;
while(number>0)
{
digit = number % 10;
number = number / 10;
digitstack.push(digit);
sum = sum+digit;
}
while(digitstack.size() > 0)
{
cout << digitstack.top() << " ";
digitstack.pop();
}
cout <<endl <<"Sum of the digits is: "<<sum<<endl;
system("PAUSE");
return EXIT_SUCCESS;
}
Oh, and BTW, keep your indentation clean. Its important.
EDIT: In response to Steve Townsend, this method is not necessarily overkill, it is just different from yours. The code can be slimmed down so that it seems less like overkill:
#include <iostream>
#include <stack>
#include <string>
using namespace std;
int getInput(string prompt)
{
int val;
cout << prompt;
cin >> val;
return val < 0 ? -val : val;
}
int main(int argc, char** argv)
{
int num = getInput("Enter a number: ");
cout << "Original Number: " << num << endl;
stack<int> digits;
int sum = 0;
while(num > 0)
{
digits.push(num % 10);
sum += digits.top();
num = num / 10;
}
while(digits.size() > 0)
{
cout << digits.top() << " ";
digits.pop();
}
cout << endl << "Sum of digits is " << sum << endl;
return 0;
}
How to split an integer into an array of digits?
>>> [int(i) for i in str(12345)]
[1, 2, 3, 4, 5]
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
*/
Split a number into its digits with Haskell
Have you heard of div and mod?
You'll probably want to reverse the list of numbers if you want to treat the most significant digit first. Converting the number into a string is an impaired way of doing things.
135 `div` 10 = 13
135 `mod` 10 = 5
Generalize into a function:
digs :: Integral x => x -> [x]
digs 0 = []
digs x = digs (x `div` 10) ++ [x `mod` 10]
Or in reverse:
digs :: Integral x => x -> [x]
digs 0 = []
digs x = x `mod` 10 : digs (x `div` 10)
This treats 0
as having no digits. A simple wrapper function can deal with that special case if you want to.
Note that this solution does not work for negative numbers (the input x
must be integral, i.e. a whole number).
Related Topics
Running My C++ Code Gives Me a Blank Console
What Do Single Quotes Do in C++ When Used on Multiple Characters
What Xml Parser Should I Use in C++
How to Call a Constructor from Another Constructor (Do Constructor Chaining) in C++
How to Convert a Std::String to Int
"Using Namespace" in C++ Headers
How to Serialize and Deserialize a Class in C++
Exotic Architectures the Standards Committees Care About
Infinite Loop With Cin When Typing String While a Number Is Expected
How to Figure Out the Parameter Type and Return Type of a Lambda
Why Do I Need Strand Per Connection When Using Boost::Asio
Pass by Reference/Value in C++
What Happens If I Define a 0-Size Array in C/C++
Why Are C Character Literals Ints Instead of Chars