Need help(Task)

Hello everyone, i need some help with a task. It says: Type in integers A and B. Find in wich number,there are less digits 2. Then multiply them. Write a function for each number.

Ex: If A is 242 and B is 200 it should say: A is 4, because 2*2, and B is 2, because 2. If A is 278252 and B is 2424252 it should say: A is 8, because 2*2*2 and B is 16, because 2*2*2*2.


Im writing again, cause some people gave me some advice. But it dosent help really much. I know how to put number into digits, but i must know how many digits it has. So im asking again, could someone write full program, or just the algorythm for finding digit 2 in the number i type?

Thanks.
> could someone write full program, or just the algorythm for finding digit 2 in the number i type?

Just the algorythm for finding digit 2 in the number i type.


1
2
3
4
5
6
int num_digits_that_are_two( unsigned int number )
{
    int num2s = 0 ;
    for( ; number > 0 ; number /= 10 ) num2s += ( number%10 == 2 ) ;
    return num2s ;
}
To find didgit 2 you can use something like this
1
2
3
4
5

int numbers[];
cin>>numbers;
didgit2=numbers[1]


It is ment to be 1 because arrays start at 0
Last edited on
Well, you don't need to know how many digits there are. The only relevant ones are 2s right? So knowing this, you can use one of the few algorithms you can find with a quick Google search to get the amount of 2s in the input. Now knowing how many 2s you have, you can then use std::pow(), which is in math.h.
----> JLBorges

(unsigned int number)


What exactly ^ its for?
Unsigned just means it can only numbers >= 0. No negative sign essentially. You gain an extra bit of range this way.

JL, I do have a question. Your algorithm is about the same that I found while looking this up, could you explain the logic behind it? I'm just not getting it I guess
-42 % 10 == -2. Or is it a positive value?

In C89 and C++98 it is implementation defined (unspecified)

In C99 and C++11, there is no ambiguity; it is -2 (result has the same sign as the dividend)


> I'm just not getting it I guess

It is extremely simply - just work out an example (say 42362527) by hand using paper and pencil and it would become obvious.

Last edited on
num2s += ( number%10 == 2 )
This will increment num2s by 1 each time (number%10 == 2)? If I'm understanding this right
Oh wow! That's pretty cool. It did become blatantly obvious once I was doing it.
Topic archived. No new replies allowed.