C++ get each digit in int - c++

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 );
}

Related

Program that checks whether another number is contained within it

I've just recently started to dabble in coding, and I ran into a problem that I haven't been able to solve for days, and the closest thing I've been able to find online is a program checking whether a number contains a specific digit, but that doesn't really apply in my case, I don't think. The problem is to let the user enter two positive numbers and check whether the reverse of the second number is contained within the first one. For example if you enter 654321 and 345, it would say say that it contains it because the reverse of 345 is 543 and 654321 contains that. Here's what I've been trying, but it has been a disaster.
P.S: The variables should stay integer through the program.
#include <iostream>
using namespace std;
bool check(int longer, int shorter)
{
int i = 1;
int rev=0;
int digit;
while (shorter > 0)
{
digit = shorter%10;
rev = rev*10 + digit;
shorter = shorter/10;
}
cout << rev << endl;
bool win=0;
int left = longer / 10; //54321
int right = longer % 10; // 65432
int middle = (longer /10)%10; // 5432
int middle1;
int middle2;
int trueorfalse = 0;
while (left > 0 && right > 0 && middle1 > 0 && middle2 >0)
{
left = longer / 10; //4321 //321
right = longer % 10; //6543 //654
middle1 = middle%10; //543
middle2= middle/10; //432
if (rev == left || rev == right || rev == middle1 || rev == middle2 || rev == middle)
{
win = true;
}
else
{
win = false;
}
}
return win;
}
int main ()
{
int longer;
int shorter;
int winorno;
cout << "Please enter two numbers, first of which is longer: ";
cin >> longer;
cin >> shorter;
winorno = check(longer,shorter);
if (winorno==true)
{
cout << "It works.";
}
else
{
cout << "It doesn't work.";
}
return 0;
}
The more you overthink the plumbing, the easier it is to
stop up the drain. -- Scotty, Star Trek III.
This becomes much easier if you divide this task in two parts:
Reverse the digits in an integer.
Search the second integer for the reversed integer calculated by the first part.
For the first part, assume that n contains the number to reverse.
int modulo=1;
int reversed_n=0;
do
{
reversed_n = reversed_n * 10 + (n % 10);
modulo *= 10;
} while ( (n /= 10) != 0);
The end result is if n contained 345, reversed_n will end up with 543, and modulo will be 1000. We'll need modulo for the second part.
The reason the loop is structured this way is intentional. If the original number is 0, we want to wind up with reversed_n also 0, and modulo as 10.
And now, we can take a similar approach to search the second number, called search, whether it contains reversed_n:
for (;;)
{
if ((search % modulo) == reversed_n)
{
std::cout << "Yes" << std::endl;
return 0;
}
if (search < modulo)
break;
search /= 10;
}
std::cout << "No" << std::endl;
Complete program:
#include <iostream>
int main()
{
int search=654321;
int n=345;
int modulo=1;
int reversed_n=0;
do
{
reversed_n = reversed_n * 10 + (n % 10);
modulo *= 10;
} while ( (n /= 10) != 0);
for (;;)
{
if ((search % modulo) == reversed_n)
{
std::cout << "Yes" << std::endl;
return 0;
}
if (search < modulo)
break;
search /= 10;
}
std::cout << "No" << std::endl;
return 0;
}
#include <iostream>
#include <cmath>
using namespace std;
int calculateNumLength(int num){
int length = 0;
while (num > 0) {
num = num / 10;
length++;
}
return length;
}
bool check(int longer, int shorter){
int reversed = 0;
int digit;
int shortLength = calculateNumLength(shorter);
int longLength = calculateNumLength(longer);
int diffrence = longLength - shortLength;
int possibleValues = diffrence + 1;
int possibleNums[possibleValues];
while ( shorter > 0 ) {
digit = shorter % 10;
rev = ( rev * 10 ) + digit;
shorter = shorter / 10;
}
int backstrip = pow(10, diffrence);
int frontstrip = pow(10, longLength-1);
int arrayCounter = 0;
while ( longer > 0 ){
possibleNums[arrayCounter++] = longer/backstrip;
if ( backstrip >= 10 ){
backstrip = backstrip / 10;
}else{
break;
}
longer = longer % frontstrip;
frontstrip = frontstrip / 10;
}
for (int i=0;i<possibleValues;i++){
if (possibleNums[i] == rev ){
return true;
}
}
return false;
}
int main() {
std::cout << check(654321,123) << std::endl;
return 0;
}

Change 'parameter' string inside method C++

it is my first question in SO, but I cannot find a good solution for this, not online nor from my brain.
I have a big string of number (over 100 digits) and I need to remove some of its digits to create a number divisible by 8. It is really simple...
However, lets say the only way to create this number is with a number that ends with '2'. In this case I would need to look for proper 10's and 100's digits and it is at this point I cannot find an elegant solution.
I have this:
bool ExistDigit(string & currentNumber, int look1) {
int currentDigit;
int length = currentNumber.length();
for (int i = length - 1; i >= 0; i--) {
currentDigit = -48;//0 in ASC II
currentDigit += currentNumber.back();//sum ASCII's value of char to current Digit
if (currentDigit == look1) {
return true;
}
else
currentNumber.pop_back;
}
return false;
}
It modify the string but since I check for 8's and 0's first, by the time I get to check 2's, the string is empty already. I solved this by creating several copies of the string, but I would like to know if there is a better way and what is it.
I know that if I use ExistDigit(string CurrentNumber, int look1), the string does not get modified, but in this case, it would not help with the 2, because after finding the two I need to look for 1's, 5's and 9's after the 2 in the original string.
What is the correct approach to these kind of problems? I mean, should I stick with changing the string or should I return a value for the position of the 2 (for example) and work from there? If it is good to change the string, how should I do it in order to be able to reuse the original string?
I am new to C++, and coding in general (just started actually) so, sorry if it is a really silly question. Thanks in advance.
EDIT: My call look like this:
int main() {
string originalNumber;//hold number. Must be string because number can be too long for ints
cin >> originalNumber;
string answer = "YES";
string strNumber;
//look for 0's and 8's. they are solutions by their own
strNumber = originalNumber;
if (ExistDigit(strNumber, 0)) {
answer += "\n0";
}
else {
strNumber = originalNumber;
if (ExistDigit(strNumber, 8)) {
answer += "\n8";
}
else {
strNumber = originalNumber;
//look for 'even'32, 'even'72, 'odd'12, 'odd'52, 'odd'92
//these are the possibilities for multiples of 8 ended with 2
if (ExistDigit(strNumber, 2)) {
if (ExistDigit(strNumber, 1)) {
}
}
else {
EDIT 2: In case you have the same problem, check the function find_last_of, it is really convenient and solves the problem.
The following code retains your design and should give at least a solution if one exists. The nested if and for can be simplified within a more elegant solution by using a recursive function. With such a recursive function, you could also enumerate all the solutions.
Instead of having multiple copies of the string, you could use an iterator that defines the start of the search. In the code the start variable is this iterator.
#include <string>
#include <iostream>
#include <sstream>
using namespace std;
bool ExistDigit(const string & currentNumber, int& start, int look1) {
int currentDigit;
int length = currentNumber.length();
for (int i = length - 1 - start; i >= 0; i--) {
currentDigit = currentNumber[i] - '0';
if (currentDigit == look1) {
start = length - i;
return true;
}
}
return false;
}
int main() {
string originalNumber;//hold number. Must be string because number can be too long for ints
cin >> originalNumber;
stringstream answer;
answer << "YES";
//look for 0's and 8's. they are solutions by their own
int start = 0;
if (ExistDigit(originalNumber, start, 0)) {
answer << "\n0";
}
else {
start = 0;
if (ExistDigit(originalNumber, start, 8)) {
answer << "\n8";
}
else {
start = 0;
//look for 'even'32, 'even'72, 'odd'12, 'odd'52, 'odd'92
//these are the possibilities for multiples of 8 ended with 2
if (ExistDigit(originalNumber, start, 2)) {
for (int look2 = 1; look2 < 10; look2 += 4) {
int startAttempt1 = start;
if (ExistDigit(originalNumber, startAttempt1, look2)) { // 'odd'
for (int look3 = 1; look3 < 10; look3 += 2) {
int startAttempt2 = startAttempt1;
if (ExistDigit(originalNumber, startAttempt2, look3))
answer << "\n" << look3 << look2 << "2";
};
}
};
for (int look2 = 3; look2 < 10; look2 += 4) {
int startAttempt1 = start;
if (ExistDigit(originalNumber, startAttempt1, look2)) // 'even'
answer << "\n" << look2 << "2";
};
}
//look for 'odd'36, 'odd'76, 'even'12, 'even'52, 'even'92
//these are the possibilities for multiples of 8 ended with 2
else if (ExistDigit(originalNumber, start, 6)) {
for (int look2 = 3; look2 < 10; look2 += 4) {
int startAttempt1 = start;
if (ExistDigit(originalNumber, startAttempt1, look2)) { // 'odd'
for (int look3 = 1; look3 < 10; look3 += 2) {
int startAttempt2 = startAttempt1;
if (ExistDigit(originalNumber, startAttempt2, look3))
answer << "\n" << look3 << look2 << "6";
};
}
};
for (int look2 = 1; look2 < 10; look2 += 4) {
int startAttempt1 = start;
if (ExistDigit(originalNumber, startAttempt1, look2)) // 'even'
answer << "\n" << look2 << "6";
};
}
//look for 'even'24, 'even'64, 'odd'44, 'odd'84, 'odd'04
//these are the possibilities for multiples of 8 ended with 2
else if (ExistDigit(originalNumber, start, 6)) {
for (int look2 = 0; look2 < 10; look2 += 4) {
int startAttempt1 = start;
if (ExistDigit(originalNumber, startAttempt1, look2)) { // 'odd'
for (int look3 = 1; look3 < 10; look3 += 2) {
int startAttempt2 = startAttempt1;
if (ExistDigit(originalNumber, startAttempt2, look3))
answer << "\n" << look3 << look2 << "4";
};
}
};
for (int look2 = 2; look2 < 10; look2 += 4) {
int startAttempt1 = start;
if (ExistDigit(originalNumber, startAttempt1, look2)) // 'even'
answer << "\n" << look2 << "4";
};
}
}
}
cout << answer.str() << std::endl;
return 0;
}
Here is a solution when you are looking for a subword composed of successive characters in the decimal textual form.
#include <string>
#include <iostream>
bool ExistDigit(const std::string& number, int look) { // look1 = 2**look
// look for a subword of size look that is divisible by 2**look = 1UL << look
for (int i = (int) number.size()-1; i >= 0; --i) {
bool hasFound = false;
unsigned long val = 0;
int shift = look-1;
if (i-shift <= 0)
shift = i;
for (; shift >= 0; --shift) {
val *= 10;
val += (number[i-shift] - '0');
};
if (val % (1UL << look) == 0)
return true;
};
return false;
}
int main(int argc, char** argv) {
std::string val;
std::cin >> val;
if (ExistsDigit(val, 3) /* since 8 = 2**3 = (1 << 3) */)
std::cout << "have found a decimal subword divisible by 8" << std::endl;
else
std::cout << "have not found any decimal subword divisible by 8" << std::endl;
return 0;
}
If you are likely to find a subword of consecutive bits in the binary form of the number, you need to convert your number in a big integer and then to do similar search.
Here is a (minimal-tested) solution without any call to an external library like gmp to convert the text in a big integer. This solution makes use of bitwise operations (<<, &).
#include <iostream>
#include <string>
#include <vector>
int
ExistDigit(const std::string & currentNumber, int look) { // look1 = 2^look
std::vector<unsigned> bigNumber;
int length = currentNumber.size();
for (int i = 0; i < length; ++i) {
unsigned carry = currentNumber[i] - '0';
// bigNumber = bigNumber * 10 + carry;
for (int index = 0; index < bigNumber.size(); ++index) {
unsigned lowPart = bigNumber[index] & ~(~0U << (sizeof(unsigned)*4));
unsigned highPart = bigNumber[index] >> (sizeof(unsigned)*4);
lowPart *= 10;
lowPart += carry;
carry = lowPart >> (sizeof(unsigned)*4);
lowPart &= ~(~0U << (sizeof(unsigned)*4));
highPart *= 10;
highPart += carry;
carry = highPart >> (sizeof(unsigned)*4);
highPart &= ~(~0U << (sizeof(unsigned)*4));
bigNumber[index] = lowPart | (highPart << (sizeof(unsigned)*4));
}
if (carry)
bigNumber.push_back(carry);
};
// here bigNumber should be a biginteger = currentNumber
for (int i = 0; i < bigNumber.size()*8*sizeof(unsigned); ++i) {
// looks for look consective bits set to '0'
bool hasFound = true;
for (int shift = 0; hasFound && shift < look; ++shift)
if (bigNumber[(i+shift) / (8*sizeof(unsigned))]
& (1U << ((i+shift) % (8*sizeof(unsigned)))) != 0)
hasFound = false;
if (hasFound) { // ok, bigNumber has look consecutive bits set to 0
// test if we are at the end of the bigNumber
int index = (i+look) / (8*sizeof(unsigned));
for (int j = ((i+look+8*sizeof(unsigned)-1) % (8*sizeof(unsigned)))+1;
j < (8*sizeof(unsigned)); j++)
if ((bigNumber[index] & (1U << j)) != 0)
return i; // the result is (currentNumber / (2^i));
while (++index < bigNumber.size())
if (bigNumber[index] != 0)
return i; // the result is (currentNumber / (2^i));
return -1;
};
};
return -1;
}
int main(int argc, char** argv) {
std::string val;
std::cin >> val;
std::cout << val << " is divided by 8 after " << ExistDigit(val, 3) << " bits." << std::endl;
return 0;
}

C++ binary input as a string to a decimal

I am trying to write a code that takes a binary number input as a string and will only accept 1's or 0's if not there should be an error message displayed. Then it should go through a loop digit by digit to convert the binary number as a string to decimal. I cant seem to get it right I have the fact that it will only accept 1's or 0's correct. But then when it gets into the calculations something messes up and I cant seem to get it correct. Currently this is the closest I believe I have to getting it working. could anyone give me a hint or help me with what i am doing wrong?
#include <iostream>
#include <string>
using namespace std;
string a;
int input();
int main()
{
input();
int decimal, x= 0, length, total = 0;
length = a.length();
// atempting to make it put the digits through a formula backwords.
for (int i = length; i >= 0; i--)
{
// Trying to make it only add the 2^x if the number is 1
if (a[i] = '1')
{
//should make total equal to the old total plus 2^x if a[i] = 1
total = total + pow(x,2);
}
//trying to let the power start at 0 and go up each run of the loop
x++;
}
cout << endl << total;
int stop;
cin >> stop;
return 0;
}
int input()
{
int x, x2, count, repeat = 0;
while (repeat == 0)
{
cout << "Enter a string representing a binary number => ";
cin >> a;
count = a.length();
for (x = 0; x < count; x++)
{
if (a[x] != '0' && a[x] != '1')
{
cout << a << " is not a string representing a binary number>" << endl;
repeat = 0;
break;
}
else
repeat = 1;
}
}
return 0;
}
I don't think that pow suits for integer calculation. In this case, you can use shift operator.
a[i] = '1' sets the value of a[i] to '1' and return '1', which is always true.
You shouldn't access a[length], which should be meaningless.
fixed code:
int main()
{
input();
int decimal, x= 0, length, total = 0;
length = a.length();
// atempting to make it put the digits through a formula backwords.
for (int i = length - 1; i >= 0; i--)
{
// Trying to make it only add the 2^x if the number is 1
if (a[i] == '1')
{
//should make total equal to the old total plus 2^x if a[i] = 1
total = total + (1 << x);
}
//trying to let the power start at 0 and go up each run of the loop
x++;
}
cout << endl << total;
int stop;
cin >> stop;
return 0;
}
I would use this approach...
#include <iostream>
using namespace std;
int main()
{
string str{ "10110011" }; // max length can be sizeof(int) X 8
int dec = 0, mask = 1;
for (int i = str.length() - 1; i >= 0; i--) {
if (str[i] == '1') {
dec |= mask;
}
mask <<= 1;
}
cout << "Decimal number is: " << dec;
// system("pause");
return 0;
}
Works for binary strings up to 32 bits. Swap out integer for long to get 64 bits.
#include <iostream>
#include <stdio.h>
#include <string>
using namespace std;
string getBinaryString(int value, unsigned int length, bool reverse) {
string output = string(length, '0');
if (!reverse) {
for (unsigned int i = 0; i < length; i++) {
if ((value & (1 << i)) != 0) {
output[i] = '1';
}
}
}
else {
for (unsigned int i = 0; i < length; i++) {
if ((value & (1 << (length - i - 1))) != 0) {
output[i] = '1';
}
}
}
return output;
}
unsigned long getInteger(const string& input, size_t lsbindex, size_t msbindex) {
unsigned long val = 0;
unsigned int offset = 0;
if (lsbindex > msbindex) {
size_t length = lsbindex - msbindex;
for (size_t i = msbindex; i <= lsbindex; i++, offset++) {
if (input[i] == '1') {
val |= (1 << (length - offset));
}
}
}
else { //lsbindex < msbindex
for (size_t i = lsbindex; i <= msbindex; i++, offset++) {
if (input[i] == '1') {
val |= (1 << offset);
}
}
}
return val;
}
int main() {
int value = 23;
cout << value << ": " << getBinaryString(value, 5, false) << endl;
string str = "01011";
cout << str << ": " << getInteger(str, 1, 3) << endl;
}
I see multiple misstages in your code.
Your for-loop should start at i = length - 1 instead of i = length.
a[i] = '1' sets a[i] to '1' and does not compare it.
pow(x,2) means and not . pow is also not designed for integer operations. Use 2*2*... or 1<<e instead.
Also there are shorter ways to achieve it. Here is a example how I would do it:
std::size_t fromBinaryString(const std::string &str)
{
std::size_t result = 0;
for (std::size_t i = 0; i < str.size(); ++i)
{
// '0' - '0' == 0 and '1' - '0' == 1.
// If you don't want to assume that, you can use if or switch
result = (result << 1) + str[i] - '0';
}
return result;
}

Finding how many a specific digit appears in array of numbers (C++)

I'm doing an online challenge and the challenge is the following:
"Kids are playing a game called "Counting digits". For given numbers S and K, they firstly write all numbers between those numbers and then count how many times each digit appears (0,1,2,3,4,5,6,7,8,9). For example, S=767, K=772, numbers will be: 767,768,769,770,771,772
So, 0 will show once (in 770), 1 will show once (in 771) and so on..
Basically, my program have to do the following (given example):
Input:
1 9
(These are numbers 1,2,3,4,5,6,7,8,9)
Output:
0 1 1 1 1 1 1 1 1 1
(0 doesn't show, other numbers show once)."
I'm stuck on this code... out of ideas.
#include <iostream>
using namespace std;
int main()
{
int s,k;
int array[10];
int c0=0,c1=0,c2=0,c3=0,c4=0,c5=0,c6=0,c7=0,c8=0,c9=0;
cin >> s >> k;
int saves = s;
int savek = k;
cout << s%10;
for(int i=s;i<=k;i++)
{
int savei=i;
while(savei!=0)
{
savei=savei%10;
}
}
Any pseudo code/snippet/code/hint is appreciated.
Purely numeric solution to a purely numeric problem:
#include <iostream>
int main()
{
int s, k, i, tmp;
std::cin >> s >> k;
int count[10] = { 0 };
for (i = s; i <= k; i++) {
tmp = i;
do {
count[tmp % 10]++;
tmp /= 10;
} while(tmp);
}
for (i = 0; i < 10; i++) {
std::cout << i << " appears " << count[i] << " times" << std::endl;
}
return 0;
}
My solution is like this:
int main(){
int s,k;
cin >> s >> k;
int numbers[10]={0};
string sum;
for(int i=s;i<=k;i++)
{
sum=to_string(i);
for(int i=0;i<sum.length();i++){
numbers[(int)sum.at(i)-48]++;
}
}
for(int i=0;i<10;i++){
cout<<numbers[i]<<endl;
}
return 0;
}
public static void getDigitsInBook(int n) {
for(int i=0;i<10;i++) {
int x = n,val=0,k=1;
while(x!=0) {
int left = x/10;
int num = x%10;
int right = n%k;
if(i == 0) {
val = val+ (left*k);
}
else if(i<num) {
val = val + ((left+1)*k);
}
else if(i==num) {
val = val + (left*k) + right+1;
}
else {
val = val+ (left*k);
}
k=k*10;
x = n/k;
}
System.out.println(val);
}
}
What you usually do with such tasks is calculating the number between 0 and S and between 0 and K and subtracting those.
How many are between 0 and 767? First count the numbers of the last digit. There are 77 times 0, 1, 2, 3, 4, 5, 6, 7 each and 76 times 8 and 9. More formally, 767/10+1 between 0 and 767%10 and 767/10+1 on the rest. Then calculate the number of occurences of the last digit for 767/10=76, multiply by 10, add 7 times 7 and 6 (for the error on the last one) and do the same for the remaining digits, here 76/10=7. Finally, add the results up.
This solves the problem in O(log_10 K).
try this code:
for(int n=s ; n<=k ; n++)
{
tempN = abs(n);
while(tempN > 0)
{
tempDigit = tempN % 10;
tempN /= 10;
//count tempDigit here
}
}
assuming your variables are ints, "tempN /= 10;" should be no problem.

How do I split an int into its digits?

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;
}