public class Solution {
public static int even;
public static int odd;
public static void main(String[] args) throws IOException {
//write your code here
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
int a = Integer.parseInt(reader.readLine());
while (a > 0) {
int remainder = a % 10;
if (a % 2 == 0)
even++;
else
odd++;
a = a / 10;
}
System.out.println("Even: " + even);
System.out.println("Odd: " + odd);
}
}
Somebody can explain to me how this code is working?
Resolved
Comments (10)
- Popular
- New
- Old
You must be signed in to leave a comment
Daniel
19 May 2020, 14:44
The reminder of number % 10 is the last digit of the number.
if reminder % 2 = 0 then the number is even, else is odd.
The number gets divided by 10 so you can get rid of the last digit.
Repeat operation.
This is how I prefer to do it.
if(a % 2 == 0) is fine too. You just don't use the reminder in the operation. 0
Ashish RajAnand
12 May 2020, 09:35
number of even number in the given input
odd...…
ex=
456322
even =4
odd=2
0
Vadim
12 May 2020, 09:48
I know that, but I want to know in detail every operation he does.
Thank you
0
Ashish RajAnand
12 May 2020, 10:04
remove line remainder=a%10;
% remainder operator ,/ division operator
a=4563;
1-time check while a>0 true
a%2==0 //false
odd=1
a=a/10 //a=456
we check for loop a>0 true
a%2==0 true;
even=even+1;//even=0+1;
a=a/10;//a=45
again check loop
a>0
a%2==0 //false
odd=odd+1; // odd=1+1=2
so on …..
+1
Vadim
12 May 2020, 13:36
I think I got it, thank you very much.
0
Guadalupe Gagnon
12 May 2020, 17:00useful
This is what I do when i try to learn how code executes:
I add a bunch of sys.out statements throughout the code at every point i am curious about. Then you can run the code and check the output to see what is going on. Sometimes it is what you would expect, but other times it may surprise you. This method takes some trial and error, but here is an example using the code you shared:
+1
Vadim
13 May 2020, 13:00
Nice explication
Thank you so much
+1
Syed Huzaifa
13 May 2020, 19:59
in the else part of your code the sys.out should be change...:)
+1
Guadalupe Gagnon
14 May 2020, 13:12
Caught me copy/pasting, which I do a lot of.
+1
Syed Huzaifa
15 May 2020, 08:16
;D
+1