# Breaking a three-digit integer. Is this a good way?

## Recommended Posts

I recently had a computer science exam and I messed it up a bit. There was an exercise to break a three digit number to three numbers. I didn't do it..because it's different to be under the pressure than in your room. So I sat and did it now. I'm asking if this is good way to do it(it works by the way)
#include <iostream>

int main()
{
int num;
std::cout << "Enter a number between 100 and 999: ";
do
{
std::cin >> num;
if( num < 100 || num > 999 )
std::cout << "100-999 please. Enter it again: ";

} while ( num < 100 || num > 999 );

int i, j, k;

for( int a = 900; a >= 100; a -= 100 )
{
if( num / a == 1 )
{
i = a / 100;
break;
}
}

for( int a = 90; a >= 10; a -= 10 )
{
if( (num - i * 100) / a == 1 )
{
j = a / 10;
break;
}

if( a == 20 )
j = 0;
}

k = num - (i * 100) - (j * 10);

std::cout << "i = " << i << ", j = " << j << ", k = " << k << "\n";

system("pause");
return 0;
}



##### Share on other sites
123 = (1 * 10 + 2) * 10 + 3123 % 10 = 3123 / 10 = 1212 % 10 = 212 / 10 = 1

Therefore, a simpler way is:

int i = num % 10;int j = (num / 10) % 10;int k = num / 100;

##### Share on other sites
Oh that was so simple :(

##### Share on other sites
Suggested exercise: Write a program that will take a number and break it into it's digits. The program should work no matter how many digits the number has (within the limits of an integer, of course).

For example, if the input is 23, the output should be 2, 3. If it's 2053, the output should be 2, 0, 5, 3, etc.

##### Share on other sites
Quote:
 Original post by Gage64Write a program that will take a number and break it into its digits.

#include <algorithm>#include <iostream>#include <iterator>#include <sstream>#include <string>int main(){    std::cout << "enter a number: ";    int i = 0;    std::cin >> i;    std::stringstream ss;    ss << i;    std::string s = ss.str();    std::copy(s.begin(), s.end() - 1, std::ostream_iterator<char>(std::cout, ", "));    std::cout << *(s.end() - 1);}

##### Share on other sites
Quote:
 Original post by DevFred*** Source Snippet Removed ***

First, the suggestion was geared towards the OP so that he'll get a better understanding of this, along with some additional practice. Posting a solution kind of gets in the way of that, don't you think?

Second, the idea was to use a method like that described by ToohrVyk (and clearly that is what should have been used in the test). In your code, you are letting the STL do all the work for you, and therefore bypassing any need to think about how to solve this yourself (unless the objective is to get some practice using the STL, but clearly that is not the case here).

##### Share on other sites
My english is so bad, it cost me more than 10 minutes to get the means,and then
find it so easy.

cout<< num/100<<endl;
cout<<(num%100)/10<<endl;
cout<<num%10<<endl;

##### Share on other sites
I'm working on it.

##### Share on other sites
Don't click. But my answer is here.
Show spoiler

##### Share on other sites
Ok, here's mine:

#include <iostream>#include <vector>#include <cmath>int main(){	int num, size = 0, a;	std::cout << "Enter a number: ";	std::cin >> num;	std::vector< int > digits;	for( int i = 10;; i*= 10 ) // get how many digits the number has	{		if( num / i == 0 )		{			a = i / 10;			size = log10( float(i));			digits.reserve(size);			break;		}	}	for( int i = a; i != 0; i/=10 ) // put the digits in the vector		digits.push_back( num / i % 10 );		for( std::vector< int >::const_iterator iter = digits.begin(); iter != digits.end(); ++iter ) // display		std::cout << *iter << " ";	std::cout << "\n";	system("pause");	return 0;}

##### Share on other sites
Either my answer is too simple (as in wrong) or yours is a bit more involved than expected.

##### Share on other sites
This would be my quick 'n' dirty solution:

void split(unsigned int number){    static const unsigned int base = 10;    if (number > base)        split(number / base);    std::cout << number % base << "\n";}int main(){    unsigned int number;    std::cin >> number;    split(number);}

Quote:
 Original post by Alpha_ProgDesEither my answer is too simple (as in wrong) or yours is a bit more involved than expected.

The implied logic of yours is correct but your actual answer wouldn't work, it's close though.

##### Share on other sites
@sheep19: Try to do it without using log10(). It will actually be simpler that way. Hint: Don't think about how many iterations the loop needs to run. Think instead of when it should stop running.

Also, note that the question simply asked you to print the digits, so there is no need to store them, and therefore no need to use an array or std::vector. The whole thing can be done in one loop.

@Alpha_ProgDes: Have you tried running your code? There are at least two problems with it (or at least one, depending on what language you are using). Try to find them without using a compiler. Also try doing it without an array like I explained above.

As a similar exercise, write a program that reads in a number and checks to see if it's a palindrom, i.e., reads the same from backwards. For example, 123 is not a palindrom, while 1221 is.

The program should not use an array or any other type of storage container, should not use log10(), and should only use one loop. Once again, it should work for any number.

##### Share on other sites
Quote:
 Original post by Gage64As a similar exercise, write a program that reads in a number and checks to see if it's a palindrom

That's laughably simple using the STL (3 lines, I think - and only one of those is the actual check), presumably though you're asking for a more "algorithm theory-esque" answer.

##### Share on other sites
Quote:
Original post by dmatter
Quote:
 Original post by Gage64As a similar exercise, write a program that reads in a number and checks to see if it's a palindrom

That's laughably simple using the STL (3 lines, I think - and only one of those is the actual check), presumably though you're asking for a more "algorithm theory-esque" answer.

Given the original post, what do you think? [wink]

The point here is to get some exercise using loops, arithmetic operations and other fundamental language constructs, not the STL. If you are using the STL for any of this, that's cheating.

##### Share on other sites
Ok, I did it again, but it displays the digits in reverse order:

do	{		i = 1;		std::cout << num / i % 10 << " ";		num /= 10;		i *= 10;	} while( num != 0 );

##### Share on other sites
Quote:
Original post by dmatter
Quote:
 Original post by Gage64As a similar exercise, write a program that reads in a number and checks to see if it's a palindrom

That's laughably simple using the STL (3 lines, I think - and only one of those is the actual check), presumably though you're asking for a more "algorithm theory-esque" answer.

Yeah I'm assuming the instructor want's to see the use of the mod operator somewhere in your solution instead of the STL since this is usually one of the questions that shows up early in a C++ course before you get to the STL.
Variations include using binary instead of decimal numbers.

p.s. To original poster I hope you at least wrote out a majority of your program and maybe some pseudocode so you can get some credit? At least that's what I would've done if I drew a blank on a test which did happen to me once and I got partial credit.

##### Share on other sites
Quote:
 Original post by sheep19Ok, I did it again, but it displays the digits in reverse order:do { i = 1; std::cout << num / i % 10 << " "; num /= 10; i *= 10; } while( num != 0 );

Think about what the i variable is actually doing there.

In order to display the symbols in order you will need some kind LIFO (Last In First Out) structure, such as a stack. My solution used recursion, which makes use of the call stack for this purpose.

##### Share on other sites
Quote:
Original post by dmatter
Quote:
 Original post by sheep19Ok, I did it again, but it displays the digits in reverse order:do { i = 1; std::cout << num / i % 10 << " "; num /= 10; i *= 10; } while( num != 0 );

Think about what the i variable is actually doing there.

Oh. I was diving by 10 and then multiplicating by 10. It's isn't needed I think.

##### Share on other sites
Quote:
 Original post by sheep19Oh. I was diving by 10 and then multiplicating by 10. It's isn't needed I think.

Well, think about what happens upon each iteration:

First Iteration:
You let i = 1
You evaluate num / i % 10 but dividing by 1 has no effect.
You let i *= 10 so now it contains the value 10.

Second Iteration:
You let i = 1 so the previous multiply is of no consequence.
You evaluate num / i % 10 but dividing by 1 has no effect.
You let i *= 10 so now it contains the value 10.

N'th Iteration:
You let i = 1 so the previous multiply is of no consequence.
You evaluate num / i % 10 but dividing by 1 has no effect.
You let i *= 10 so now it contains the value 10.

In short, you have a variable that you're manipulating but it has no side effects and so could be removed entirely. [smile]

##### Share on other sites
OK, looks like I didn't think this through. Doing this in one loop without an array and with no helper functions seems to be trickier than I thought (if it's even possible).

It's still possible to do this in one loop with no array, but with some math functions, but it's a bit more involved than what I had in mind.

##### Share on other sites
Well:

#include <iostream>int main(){	int num, i = 0;	std::cout << "Enter a number: ";	std::cin >> num;	do	{		if( i == 0 )		{			i = 1;			do			{				i *= 10;			} while( num / i != 0 );			i /= 10;		}		std::cout << num / i % 10 << " ";		i /= 10;	} while( i != 0 );	system("pause");	return 0;}

It works by the way. :)

##### Share on other sites
@sheep19: Well done!

BTW, your loops don't need to be nested, you can just write them as two separate loops, one after the other.

##### Share on other sites
Thank you! :)

Quote:
 Original post by Gage64As a similar exercise, write a program that reads in a number and checks to see if it's a palindrom, i.e., reads the same from backwards. For example, 123 is not a palindrom, while 1221 is.The program should not use an array or any other type of storage container, should not use log10(), and should only use one loop. Once again, it should work for any number.

I know it was meant for the the other exercise, but ok, it's no big deal (although two separated loops would have cleaner syntax).

Thanks to everyone for the help, I really appreciate it!
-------------------------------- ---------------------------------

Ok, now for the next one. Is 4564 palindrom? or only 4554?

##### Share on other sites
Quote:
 Original post by sheep19Is 4564 palindrom?

4564 in reverse is 4654 which is not equal to 4564, so it's not a palindrom.

## Create an account

Register a new account

• ### Forum Statistics

• Total Topics
628334
• Total Posts
2982147

• 9
• 24
• 9
• 9
• 13