How do I split an int into its digits? - c++

How can I split an int in c++ to its single numbers? For example, I'd like to split 23 to 2 and 3.

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.

Reversed order digit extractor (eg. for 23 will be 3 and 2):
while (number > 0)
{
int digit = number%10;
number /= 10;
//print digit
}
Normal order digit extractor (eg. for 23 will be 2 and 3):
std::stack<int> sd;
while (number > 0)
{
int digit = number%10;
number /= 10;
sd.push(digit);
}
while (!sd.empty())
{
int digit = sd.top();
sd.pop();
//print digit
}

The following will do the trick
void splitNumber(std::list<int>& digits, int number) {
if (0 == number) {
digits.push_back(0);
} else {
while (number != 0) {
int last = number % 10;
digits.push_front(last);
number = (number - last) / 10;
}
}
}

A simple answer to this question can be:
Read A Number "n" From The User.
Using While Loop Make Sure Its Not Zero.
Take modulus 10 Of The Number "n"..This Will Give You Its Last Digit.
Then Divide The Number "n" By 10..This Removes The Last Digit of Number
"n" since in int decimal part is omitted.
Display Out The Number.
I Think It Will Help. I Used Simple Code Like:
#include <iostream>
using namespace std;
int main()
{int n,r;
cout<<"Enter Your Number:";
cin>>n;
while(n!=0)
{
r=n%10;
n=n/10;
cout<<r;
}
cout<<endl;
system("PAUSE");
return 0;
}

cast it to a string or char[] and loop on it

the classic trick is to use modulo 10:
x%10 gives you the first digit(ie the units digit). For others, you'll need to divide first(as shown by many other posts already)
Here's a little function to get all the digits into a vector(which is what you seem to want to do):
using namespace std;
vector<int> digits(int x){
vector<int> returnValue;
while(x>=10){
returnValue.push_back(x%10);//take digit
x=x/10; //or x/=10 if you like brevity
}
//don't forget the last digit!
returnValue.push_back(x);
return returnValue;
}

Declare an Array and store Individual digits to the array like this
int num, temp, digits = 0, s, td=1;
int d[10];
cout << "Enter the Number: ";
cin >> num;
temp = num;
do{
++digits;
temp /= 10;
} while (temp);
for (int i = 0; i < digits-1; i++)
{
td *= 10;
}
s = num;
for (int i = 0; i < digits; i++)
{
d[i] = s / td %10;
td /= 10;
}

int n = 1234;
std::string nstr = std::to_string(n);
std::cout << nstr[0]; // nstr[0] -> 1
I think this is the easiest way.
We need to use std::to_string() function to convert our int to string so it will automatically create the array with our digits. We can access them simply using index - nstr[0] will show 1;

Start with the highest power of ten that fits into an int on your platform (for 32 bit int: 1.000.000.000) and perform an integer division by it. The result is the leftmost digit. Subtract this result multipled with the divisor from the original number, then continue the same game with the next lower power of ten and iterate until you reach 1.

You can just use a sequence of x/10.0f and std::floor operations to have "math approach".
Or you can also use boost::lexical_cast(the_number) to obtain a string and then you can simply do the_string.c_str()[i] to access the individual characters (the "string approach").

I don't necessarily recommend this (it's more efficient to work with the number rather than converting it to a string), but it's easy and it works :)
#include <algorithm>
#include <iostream>
#include <iterator>
#include <string>
#include <boost/lexical_cast.hpp>
int main()
{
int n = 23984;
std::string s = boost::lexical_cast<std::string>(n);
std::copy(s.begin(), s.end(), std::ostream_iterator<char>(std::cout, "\n"));
return 0;
}

int n;//say 12345
string s;
scanf("%d",&n);
sprintf(s,"%5d",n);
Now you can access each digit via s[0], s[1], etc

You can count how many digits you want to print first
#include <iostream>
#include <cmath>
using namespace std;
int main(){
int number, result, counter=0, zeros;
do{
cout << "Introduce un numero entero: ";
cin >> number;
}while (number < 0);
// We count how many digits we are going print
for(int i = number; i > 0; i = i/10)
counter++;
while(number > 0){
zeros = pow(10, counter - 1);
result = number / zeros;
number = number % zeros;
counter--;
//Muestra resultados
cout << " " << result;
}
cout<<endl;
}

Based on icecrime's answer I wrote this function
std::vector<int> intToDigits(int num_)
{
std::vector<int> ret;
string iStr = to_string(num_);
for (int i = iStr.size() - 1; i >= 0; --i)
{
int units = pow(10, i);
int digit = num_ / units % 10;
ret.push_back(digit);
}
return ret;
}

int power(int n, int b) {
int number;
number = pow(n, b);
return number;
}
void NumberOfDigits() {
int n, a;
printf("Eneter number \n");
scanf_s("%d", &n);
int i = 0;
do{
i++;
} while (n / pow(10, i) > 1);
printf("Number of digits is: \t %d \n", i);
for (int j = i-1; j >= 0; j--) {
a = n / power(10, j) % 10;
printf("%d \n", a);
}
}
int main(void) {
NumberOfDigits();
}

#include <iostream>
using namespace std;
int main()
{
int n1 ;
cout <<"Please enter five digits number: ";
cin >> n1;
cout << n1 / 10000 % 10 << " ";
cout << n1 / 1000 % 10 << " ";
cout << n1 / 100 % 10 << " ";
cout << n1 / 10 % 10 << " ";
cout << n1 % 10 << " :)";
cout << endl;
return 0;
}

Related

I am not getting desired output in reverse a number code in C++

I am trying to find a reversed number and check that it is a palindrome or not from a different approach but I was getting a right reversed number up to two digits and if the digits are more than two then I am getting wrong output. I cannot understand why is this so as I think my code is right.
below is the code
#include <iostream>
#include <math.h>
using namespace std;
int main()
{
int num, rem, t, add;
cin >> t;
while (t--) {
int total = 0, count = 0, i = 1, quo = 0;
cin >> num;
quo = num;
while (quo > 9) //count determiner
{
quo = quo / 10;
++count;
}
while (count >= 0) //reverse number saved in total
{
int den = pow(10, i);
rem = (num % den);
add = rem / pow(10, i - 1);
total = total + (add * pow(10, count));
++i;
--count;
}
if (total == num) {
cout << "Palindrome"
<< "\n";
}
else {
cout << "Not a Palindrome"
<< "\n";
}
}
return 0;
}
please help me to know where I am going wrong in this code.
I don't understand your code. so i assumed by myself and wrote code.I assume that there will be no negative number and if there will be then i rid off negative sign. please provide desire output for negative number.
#include <iostream>
using namespace std;
int main()
{
//int num, rem, t, add;
int t;
cin >> t;
while (t-- > 0) {
int n;
cin >> n;
int num = abs(n);
if (n < 0)
{
n = abs(n);
}
int res{ 0 };
while (n > 0)
{
res *= 10;
int rem = n % 10;
res += rem;
n /= 10;
}
if (res == num) {
cout << "Palindrome"
<< "\n";
}
else {
cout << "Not a Palindrome"
<< "\n";
}
}
return 0;
}
ouptut of above code:
4
-191
Palindrome
232
Palindrome
123
Not a Palindrome
561
Not a Palindrome
Your code to reverse a number is very convoluted, as it uses pow (a floating point function) to get each digit. This is totally unnecessary if you look for the pattern of how to reverse an integer.
Simple addition, multiplying by 10, and modulus is all that's necessary to do this. Note that I created a function, so that it is easy to follow:
#include <cmath>
#include <iostream>
int reverse_int(int num)
{
int total = 0;
// take care of negative by using absolute value
int tempNum = abs(num);
while (tempNum > 0)
{
total = (total*10) + (tempNum % 10);
tempNum /= 10;
}
return (num < 0)?-total:total;
}
int main()
{
int num = 1234321;
if ( num == reverse_int(num))
std::cout << num << " is a palindrome\n";
else
std::cout << num << " is not a palindrome\n";
int num2 = 123;
if ( num2 == reverse_int(num2))
std::cout << num2 << " is a palindrome\n";
else
std::cout << num2 << " is not a palindrome\n";
}
Output:
1234321 is a palindrome
123 is not a palindrome
The loop is very simple if you follow what is going on:
number = 123 (Assume this is our number)
total = 0;
Loop while (number > 0):
First iteration:
total = (total * 10) + (number % 10) --> (0 * 10) + (0 % 3) --> 3
number /= 10 --> 12
Second iteration:
total = (total * 10) + (number % 10) = (3 * 10) + (12 % 10) --> 32
number /= 10 --> 1
Third iteration:
total = (total * 10) + (number % 10) = (32 * 10) + (1 % 10) --> 321
number /= 10 --> 0 (Stop the loop)
total = 321
At the end of the function, we just return the value, and make it negative if the original number was negative.
You are not checking if the input was valid. So if we leave that aside and assume the input is a valid integer then you can use a std::string and reverse it via std::reverse:
#include <string>
#include <algorithm>
#include <iostream>
int main() {
std::string input;
std::cin >> input;
std::string reverse = input;
std::reverse(reverse.begin(),reverse.end());
if (input == reverse) std::cout << "Palindrome number"
}

Large digit numbers

The program is simple. The user inputs n and n amount of numbers and i try to add zeros in between adjacent digits. For example if the user enters 9(n) digits as 1 2 3 4 5 6 7 8 9 (spaced out), the program outputs 10203040506070809. The program works well for up to n=8 digits but i get funny answers from n=9 digits upwards. The range of n should be 3<=n<=15 . My program is as follows:
int main()
{
cout << "\nEnter n and n values: \n";
int n;
cin >> n;
vector<long long>nums;
int en = n;
while (en > 0)
{
long long x;
cin >> x;
nums.push_back(x);
--en;
}
int r = 2 * n - 2;
long long new_val = 0;
int j = 0;
for (int i = 0; i < n; ++i)
{
new_val = new_val + nums[i] * (pow(10, r - j));
j += 2;
}
cout << new_val << endl;
}
I don't know how to solve the issue of funny answers from n=9 to n=15.
The main problem is long long is only 64-bits in size, and thus can only hold up to 19 digits. Its maximum value is 9,223,372,036,854,775,807.
It is possible to make your code work correctly up to n=10 if you simply remove pow() (which operates on floating-point types, not integer types). For the 2nd and subsequent loop iterations, you can simply multiply new_val by 100 before adding nums[i]:
#include <iostream>
#include <vector>
using namespace std;
int main()
{
cout << "\nEnter n and n values: \n";
int n;
cin >> n;
vector<long long> nums;
int en = n;
while (en > 0)
{
long long x;
cin >> x;
nums.push_back(x);
--en;
}
long long new_val = 0;
if (n > 0)
{
new_val = nums[0];
for (int i = 1; i < n; ++i)
{
new_val *= 100;
new_val += nums[i];
}
}
cout << new_val << endl;
}
Live Demo
However, 1020304050607080901 is 19 digits, so n>=11 will overflow past the max value of long long.
Live Demo
For such high values, you need to use a BigNumber library (as most compilers do not yet have a native 128-bit numeric type). Or, just use std::string instead of long long:
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
using namespace std;
int main()
{
cout << "\nEnter n and n values: \n";
int n;
cin >> n;
vector<int> nums;
int en = n;
while (en > 0)
{
int x;
cin >> x;
nums.push_back(x);
--en;
}
ostringstream new_val;
if (n > 0)
{
new_val << nums[0];
for (int i = 1; i < n; ++i)
new_val << '0' << nums[i];
}
cout << new_val.str() << endl;
}
Live Demo
Allow me to suggest a different approach to this problem. Since containers will give you trouble holding those large numbers, then don't with them as numbers, try string instead:
After you get the numbers from the user and store them in the nums vector, do the following:
string output = "";
char temp;
for (int i = 0; i < nums.size(); i++){
temp = nums [i] + '0';
output += temp;
if (i != (nums.size()-1))
output += "0";
}
cout << output;
Using this method, the user can enter any number as large as they want. If you want the number to be from 9 to 15, you can simply add validation at the beginning without having to deal with complicated containers.

how can i remove all digits before some specific digit

How can i remove all digits from number before finding specific digit.
Let's say i want to get all digits after digit 1 (1-included)
Example: 3543125 - i want to get digits 125
i started doing this:
int n, result;
cout << "Please enter number: ";
cin >> n;
while (n>0)
{
n = n % 10;
}
to get last digit, but i don't know how you can save it in variable and then add the second digit to it.
Can someone please explain, how can i solve this?
Here is an algorithm I didn't test it but it works {only with loops and if}
int num = 3543125;
int temp = 0;
do //get the result in reverse number
{
temp += num % 10;
temp *= 10;
num /= 10;
if (num % 10 == 1)
temp += 1;
} while (num % 10 != 1);
int result = 0;
while (temp > 0) //reverse the temp number to result
{
result = result * 10 + (temp % 10);
temp = temp / 10;
}
cout << result; // = 125
Try this one. (too simple :-) )
#include <math.h>
int n,a, result=0;
cout << "Please enter number: ";
cin >> n;
cout << "Please enter number of digits: ";
cin >> a;
int b=a;
while(b>0) {
result += n%10 * pow(10,a-b--);
n=n%10;
}
std::cout<<"result: "<<result;

C decimal to binary without arrays

I think I've almost got it, but I feel like I'm go in circles trying to figure this out.
The challenge to out cout without using strings or arrays. I took the number 56 as an example and 56 should equal 111000 this is not the case as it goes through fine till 7 then the number equals number*2 + number%2 makes it equal to 15 and outputs all 1's. Idk anymore, this is driving me to the moon and back.
#include <iostream>
using namespace std;
int main()
{
int number = 0;
int n = 1;
int x = n;
cin>>number;
cout<<n%2;
while(n <= number)
{
if(n%2 == 0)
{
n = n*2;
cout<<0;
}
else
{
n = n*2 + n%2;
cout<<n%2;
}
}
}
You can use the binary operator & to check if a single bit is 1 or 0.
for (int i=512; i>0; i/=2) {
cout << ( ( number & i ) != 0 ) ;
}
Note that this WILL print leading 0's.
Also, I'm assuming you only want to print positive integers.
Alternative:
for (int i=512; i>0; i/=2) {
if (number >= i) {
cout << 1;
number -= i;
} else {
count << 0;
}
}
You can use recursion
void decimal_to_binary(int decimal)
{
int remainder = decimal % 2;
if (decimal < 1)
return;
decimal_to_binary(decimal / 2);
cout << remainder;
}
This function will take the decimal, get its remainder when divided to 2. Before it the function call itself again, it checks if the decimal is less than 1(probably 0) and return to execute the printing of 1's and 0's
I had this type of problem assigned to me recently. This code example work up to a maximum of 10 binary digits (per the problem guidelines) and keep prompting for input until 0 is entered (sentinel value). This can certainly be improved but the math is correct:
#include <iostream>
#include <cmath>
using namespace std;
int main ()
{
//Declare Variables
int inputValue = 0;
int workingValue = 0;
int conversionSum = 0;
//Begin Loop
do{
//Prompt for input
cout << "Enter a binary integer (0 to quit): ";
cin >> inputValue;
//Reset Variables
workingValue = inputValue;
conversionSum = 0;
//Begin processing input
//10 digits max, so 10 iterations
for (int i=0; i<10; i++) {
//Check for non-binary entry
if ((workingValue % 10) != 1 && (workingValue % 10 != 0)){
cout << "Invalid!\n";
workingValue = 0;
conversionSum = 0;
break;
}
//check to see if 2^i should be added to sum
if (workingValue%2 == 1){
conversionSum += pow(2,i);
workingValue--;
}
//divide by 10 and continue loop
workingValue= workingValue / 10;
}
//output results
cout << "converted to decimal is: " << conversionSum << endl;
}while (inputValue != 0);
}
#include<iostream>
#include<cmath>
using namespace std;
int main()
{
cout << "enter a number";
int number, n, a=0;
cin >> number;
n = number;
do
{
n=n/2;
a=a+1;
}
while (n>=1);
cout << "a is" << a;
int c = a;
int b = a;
cout << "binary is";
for(int i=0; i<=c; i++)
{
int k = number / pow(2,b);
cout << k;
number = number - k * pow(2,b);
b = b-1;
}
return 0;
}
Although asked in C I have used C++. I have used the logic that if you have to convert decimal to binary we have to find the maximum power of 2 contained in the number which when added by 1 becomes the number of digit of required binary .. leftmost digit is the number of highest available power of 2 (ex in 8 highest power of 2 is 3 and 1 such is available)...then subtract this from the number and (ex 8-8=0)and search for number of next highest available power of 2 and so on.

C++ get each digit in int

I have an integer:
int iNums = 12476;
And now I want to get each digit from iNums as integer. Something like:
foreach(iNum in iNums){
printf("%i-", iNum);
}
So the output would be: "1-2-4-7-6-".
But i actually need each digit as int not as char.
Thanks for help.
void print_each_digit(int x)
{
if(x >= 10)
print_each_digit(x / 10);
int digit = x % 10;
std::cout << digit << '\n';
}
Convert it to string, then iterate over the characters. For the conversion you may use std::ostringstream, e.g.:
int iNums = 12476;
std::ostringstream os;
os << iNums;
std::string digits = os.str();
Btw the generally used term (for what you call "number") is "digit" - please use it, as it makes the title of your post much more understandable :-)
Here is a more generic though recursive solution that yields a vector of digits:
void collect_digits(std::vector<int>& digits, unsigned long num) {
if (num > 9) {
collect_digits(digits, num / 10);
}
digits.push_back(num % 10);
}
Being that there are is a relatively small number of digits, the recursion is neatly bounded.
Here is the way to perform this action, but by this you will get in reverse order.
int num;
short temp = 0;
cin>>num;
while(num!=0){
temp = num%10;
//here you will get its element one by one but in reverse order
//you can perform your action here.
num /= 10;
}
I don't test it just write what is in my head. excuse for any syntax error
Here is online ideone demo
vector <int> v;
int i = ....
while(i != 0 ){
cout << i%10 << " - "; // reverse order
v.push_back(i%10);
i = i/10;
}
cout << endl;
for(int i=v.size()-1; i>=0; i--){
cout << v[i] << " - "; // linear
}
To get digit at "pos" position (starting at position 1 as Least Significant Digit (LSD)):
digit = (int)(number/pow(10,(pos-1))) % 10;
Example: number = 57820 --> pos = 4 --> digit = 7
To sequentially get digits:
int num_digits = floor( log10(abs(number?number:1)) + 1 );
for(; num_digits; num_digits--, number/=10) {
std::cout << number % 10 << " ";
}
Example: number = 57820 --> output: 0 2 8 7 5
You can do it with this function:
void printDigits(int number) {
if (number < 0) { // Handling negative number
printf('-');
number *= -1;
}
if (number == 0) { // Handling zero
printf('0');
}
while (number > 0) { // Printing the number
printf("%d-", number % 10);
number /= 10;
}
}
Drawn from D.Shawley's answer, can go a bit further to completely answer by outputing the result:
void stream_digits(std::ostream& output, int num, const std::string& delimiter = "")
{
if (num) {
stream_digits(output, num/10, delimiter);
output << static_cast<char>('0' + (num % 10)) << delimiter;
}
}
void splitDigits()
{
int num = 12476;
stream_digits(std::cout, num, "-");
std::cout << std::endl;
}
I don't know if this is faster or slower or worthless, but this would be an alternative:
int iNums = 12476;
string numString;
stringstream ss;
ss << iNums;
numString = ss.str();
for (int i = 0; i < numString.length(); i++) {
int myInt = static_cast<int>(numString[i] - '0'); // '0' = 48
printf("%i-", myInt);
}
I point this out as iNums alludes to possibly being user input, and if the user input was a string in the first place you wouldn't need to go through the hassle of converting the int to a string.
(to_string could be used in c++11)
I know this is an old post, but all of these answers were unacceptable to me, so I wrote my own!
My purpose was for rendering a number to a screen, hence the function names.
void RenderNumber(int to_print)
{
if (to_print < 0)
{
RenderMinusSign()
RenderNumber(-to_print);
}
else
{
int digits = 1; // Assume if 0 is entered we want to print 0 (i.e. minimum of 1 digit)
int max = 10;
while (to_print >= max) // find how many digits the number is
{
max *= 10;
digits ++;
}
for (int i = 0; i < digits; i++) // loop through each digit
{
max /= 10;
int num = to_print / max; // isolate first digit
to_print -= num * max; // subtract first digit from number
RenderDigit(num);
}
}
}
Based on #Abyx's answer, but uses div so that only 1 division is done per digit.
#include <cstdlib>
#include <iostream>
void print_each_digit(int x)
{
div_t q = div(x, 10);
if (q.quot)
print_each_digit(q.quot);
std::cout << q.rem << '-';
}
int main()
{
print_each_digit(12476);
std::cout << std::endl;
return 0;
}
Output:
1-2-4-7-6-
N.B. Only works for non-negative ints.
My solution:
void getSumDigits(int n) {
std::vector<int> int_to_vec;
while(n>0)
{
int_to_vec.push_back(n%10);
n=n/10;
}
int sum;
for(int i=0;i<int_to_vec.size();i++)
{
sum+=int_to_vec.at(i);
}
std::cout << sum << ' ';
}
The answer I've used is this simple function:
int getDigit(int n, int position) {
return (n%(int)pow(10, position) - (n % (int)pow(10, position-1))) / (int)pow(10, position-1);
}
Hope someone finds this helpful!
// Online C++ compiler to run C++ program online
#include <iostream>
#include <cmath>
int main() {
int iNums = 123458;
// int iNumsSize = 5;
int iNumsSize = trunc(log10(iNums)) + 1; // Find length of int value
for (int i=iNumsSize-1; i>=0; i--) {
int y = pow(10, i);
// The pow() function returns the result of the first argument raised to
the power of the second argument.
int z = iNums/y;
int x2 = iNums / (y * 10);
printf("%d ",z - x2*10 ); // Print Values
}
return 0;
}
You can do it using a while loop and the modulo operators.
It just gives the digits in the revese order.
int main() {
int iNums = 12476;
int iNum = 0;
while(iNums > 0) {
iNum = iNums % 10;
cout << iNum;
iNums = iNums / 10;
}
}
int a;
cout << "Enter a number: ";
cin >> a;
while (a > 0) {
cout << a % 10 << endl;
a = a / 10;
}
int iNums = 12345;
int iNumsSize = 5;
for (int i=iNumsSize-1; i>=0; i--) {
int y = pow(10, i);
int z = iNums/y;
int x2 = iNums / (y * 10);
printf("%d-",z - x2*10 );
}