Could you explain me how this code works? I have tried it with any input and it always gives right result. I think that they key its the line reversenum = reversenum * 10;but i need some explanation on it.
public static void main(String args[]) {
int num=123456789;
int reversenum =0;
while( num != 0 ){
reversenum = reversenum * 10;
reversenum = reversenum + num%10;
num = num/10;
}
System.out.println("Reverse of specified number is: "+reversenum);
}
You start with 123456789 (num) and 0 (reversenum). Then, you multiply reversenum by 10: it remains 0. num % 10 is the remainder when num is divided by 10: this is 9, which becomes reversenum. num is then divided by 10, but integer division gets the floor of fractional results, so you will get 12345678 as num (NOT 12345678.9). In the second pass, 9 (reversenum) is multiplied by 10 to get 90, and the last digit of num is added: 8. reversenum becomes 98 and num becomes 1234567. This keeps going until num is 0 and reversenum is 987654321; the while loop's condition will then be satisfied.
Essentially, what the code does is:
Take off the units digit from the original number.
Add that digit to the rightmost position of the reverse.
Multiply the reverse by 10, so the digit shifts up one.
Divide the original by 10, to move on to the next digit.
This happens until there are no more digits left.
At the end of each pass through the while loop, the current last digit of num is removed and it becomes the last digit of reversenum. So the last digit of num is removed and it becomes the first digit added to reversenum (and thus the first digit of reversenum). Then it takes what was originally the next to last digit of num and it becomes the second digit added to reversenum (and thus the second digit of reversenum). This continues until no digits are left to move.
Let's look at the first pass:
reversenum becomes 0*10, which is 0. Then you add num%10, which is 9. So reversenum becomes 9.
Meanwhile the integer division makes num become 12345678
Looking at the next pass:
reversnum becomes 9*10 which is 90, then add num%10 which is 8, so reversenum becomes 98.
Meanwhile integer division makes num become 1234567.
small warning
What would you think the reverse of 90 is? You should be aware of this case.
Let your number be 12345. We extract the digits from the end. First we find the remainder when 12345 divided by 10. The remainder comes to be 5.Now we add this to our reversenum which is supposed to store the reverse number. Then we divide 12345 by 10 . As a integer divided by a integer gives a integer value . Therefore
num = 12345/10 = 1234
We multiply
reversenum by 10 so that reversenum becomes 50 and again add the remainder to reversenum So 2nd time reversenum becomes 54.Then we extract the last digit of 1234 (num variable). As you can see this continues till the total number is reversed i.e, num=0 (there are no more digits to be extracted).
Inside the while statement it is multiplying the reversenum variable by ten, then adding the remainder of the num/10 to reversenum, and then finally it divides the num by ten. It is possible for this while statement to end because since each variable is an int, dividing num by ten will always produce the rounded up version of num/10 if num is not evenly divisible by 10.
Related
Could anyone explain how does this method works.
public static int calculate(int n){
if (n/10 == 0)
return n;
else
return (n % 10 + calculate(n/10));
}
I input n = 15 and it get a 6 but I don't understand how the method works. please help. thank you.
The method calculates the sum of the digits.
If the n is smaller than 10, you simply return n (since the sum of digits of a single digit number is the number itself).
Otherwise you add the least significant digit (that's n % 10) to the sum of digits of the number n / 10 (which is calculated recursively).
For n = 15 , here is how it works
15/10 > 0 , so the else condition is executed.
15%10 + calculate(15/10) i.e 5 + calculate(1).
The method is called again for n = 1;
Since 1/10 == 0 , 1 is returned
This 1 is then added to 5.
Therefore answer is 6.
So what this function does is return the sum of the digits that make up the number.
It goes like this:
calculate(15);
evaluates to
15%10 + calculate(1);
evaluates to
5 + 1;
which in the end; sums up to 6.
In other words; the above is an recursive approach to sum all the digits in a number. You could easily re-write this using a simple loop to avoid the recursion construct.
It cuts off the most right digit and moves on recursively with the rest of the number. (line 5)
If we have only one digit left (line 2), it is also added to the sum and the algorithm ends. (line 3)
In this example there is a if else condition so on the basis of input parameter there are 2 conditions '
-Firstly it checks in the if condition (n/10 == 0) .
-Consider your input as n=15.
now it checks if (n/10 == 0) i.e 15/10==0 which is false because 15/10=5 which is not equal to 0.
-As the condition is false it moves to else block where condition is to return
(n % 10 + calculate(n/10)
i.e. (15%10 +15/10)==5+1==6
-So the return is 6.
I m not understanding the meaning of using this lines
this are on the while block.
import java.util.Scanner;
public class ReverseNumberWhile {
public static void main(String[] args){
int num = 0;
int reversenum = 0;
System.out.println("Enter your number and press enter: ");
Scanner input = new Scanner(System.in);
num = input.nextInt();
while(num != 0) {
reversenum = reversenum * 10;
reversenum = reversenum + num%10;
num = num/10;
}
System.out.println("Reverse of input number is: " + reversenum);
}
}
There you go,commented :
while(num != 0)
{
reversenum = reversenum * 10; //This moves the reversenum attained in previous iteration to one higher place value
reversenum = reversenum + num%10; // num%10 gives you the last digit which is added to the existing reversenum
num = num/10; //This leaves the remaining digits removing rightmost
}
This code produces the number reversenum with the same digits as num, but in reversed order. For example, if num==12345, then reversenum==54321. It works by chopping the digits of num one-by-one, starting with the last one, and adding them to reversenum. The loop can be described as follows:
Append the last digit of num to reversenum (the first two lines).
Remove the last digit of num (the last line).
This repeats as long as there are any digits left in num, that is, while it's non-zero.
The first two lines can actually be written as a single line:
reversenum = reversenum * 10 + num % 10;
This way it actually makes more sense because you can see what's going on here: we take reversenum, shift its digits to the left (by multiplying by 10) and then add the last digit of num (which is obtained by num % 10).
I have a method and I am interested in knowing how it actually works. I have searched the internet, but to no avail. This method when used returns the first digit of an entered integer in to an array.
What puzzles me is the divide AND operator. I know that the operator divides an operand on the left with the operator on the right and applies the answer to the left side.
Here is the method:
public static int firstDigit(int index)
{
while (index > 9)
index /= 10;
return (index);
}
In my program when an integer is entered, say 100 it reads out the number 1, as its the first number of the entered integer.
shouldn't this answer be 10, because index = 100 /= 10 = 10?
Sorry if im doing it wrong, i'm new here and at programming, i did a considerable amount of research before i asked this question.
shouldn't this answer be 10, because index = 100 /= 10 = 10?
No. 10 is more than 9, so it divides it again.
The key part here is the while loop. In the function above, it was written without brackets, but it could be rewritten as
public static int firstDigit(int index)
{
while (index > 9)
{
index /= 10;
}
return (index);
}
I'm not going to explain what a while loop is in detail, but it basically repeats the process while the condition is true.
So in the case of 100, it does this:
"Is index more than 9?" Yes. Set index to index/10. (Index now equals 10). "Is index more than 9?" Yes. Set index to index/10. (Index now equals 1). "Is index more than 9?" No. Return index. (1).
In the case of 99, it does this:
"Is index more than 9?" Yes. Set index to index/10. (Index now equals 9.9, round that to 9). "Is index more than 9?" No. Return index. (9).
Suppose the input is 100 :
You start with index = 100
then index = index / 10 = 10
since 10 > 9, you divide by 10 again :
index = index / 10 = 1
Then you exit the loop and return 1.
Basically, what this method does is compute index / 10^(n-1), where n is the number of digits. This gives you the most significant digit.
The line with while in it means that the following line (the one that does the division) happens repeatedly until the number that's left is less than ten. So 100 is divided by 10 to give 10, and then 10 is divided by 10 to give 1, which is returned.
shouldn't this answer be 10, because index = 100 /= 10 = 10?
No, it shouldn't. Why? Because of the while loop
while (index > 9)
in the first iteration, index enters in the loop as 100, and it is modified to 100/10 = 10.
Then, the condition index > 9 is evaluated. Since it's true (10 > 9) the program continues with the next iteration. Therefore, index is modified to 10/10 = 1.
The condition is evaluated again index > 9, but this time it's false (1 > 9), so the program exits the loop and returns the last value of index, 1.
How can I count the 0s after a decimal point? For example, 0.0003 has 3 zeros, 0.03 has 1 zero and 0.00000045 has 6 zeros.
One approach is to keep multiplying by 10 until your number is greater than one; then count how many times you had to multiply by 10 and subtract 1.
double num = 0.00000045;
int zeros = 0;
while (num < 1) {
num *= 10;
zeros++;
}
zeros -= 1;
System.out.println(zeros);
6
If you have other non-zero digits before the decimal point, you can trim those off with something like num = num % 1. If your number is negative, then just take its absolute value.
(int)Math.log10(1/(x%1))
I think this short formula should work correct [for positive x - if it can be negative, we add taking of absolute value] - or there are some cases when it doesn't?
You could do this using Strings. First get a substring of digits after decimal point. Then convert that into a char array. Then loop through it and count the number of zeroes.
From Java Malik textbook- determine if an number is divisible by 11..
Code Solution provided:
import java.util.*;
public class Divby11
{
static Scanner console = new Scanner(System.in);
public static void main (String[] args)
{
int num, temp, sum;
char sign;
System.out.print("Enter a positive integer: ");
num = console.nextInt();
System.out.println();
temp = num;
sum = 0;
sign = '+';
do
{
switch (sign)
{
case '+' :
sum = sum + num % 10;
sign = '-';
break;
case '-' :
sum = sum - num % 10;
sign = '+';
}
num = num / 10; //remove the last digit
}
while (num > 0);
if (sum % 11 == 0)
System.out.println(temp + " is divisible by 11");
else
System.out.println(temp + " is not divisible by 11");
}
Why go through all the effort above and just say...
if (sum % 11 == 0)
System.out.println(temp + " is divisible by 11");
else
System.out.println(temp + " is not divisible by 11");
Can any of you experts see why the author would do it this way (long way)?
for the Divisibility Rule of 11:
form the alternating sum of the digits
if this sum is divisible for 11 then the number is divisible for 11
Examples
68090 = 0 - 9 + 0 - 8 + 6 = -11 => TRUE
493827 = 7 - 2 + 8 - 3 + 9 - 4 = 15 = 4 => FALSE
This code example isn't actually dividing by eleven. If you see, it's alternating between adding and subtracting each digit, then checks at the very end if the result is divisible by 11.
For example, look at the following number and how this algorithm works with it:
Start with sum=0, sign='+', num=517
First iteration: sum=7, sign='-', num=51
Second iteration: sum=6, sign='+', num=5
Final iteration: sum=11, sign='-', num=0
The final result is divisible by eleven.
EDIT: The algorithm does indeed look to be implementing the divisibility rule for 11 as dfa mentions in his answer.
You will have to provide more context from the book as to what the author was trying to demonstrate. This code example does not check to see if the number entered is divisible by 11. What it does is it adds every other digit, subtracts every other digit and then checks THAT number to see if it's divisible by 10.
EX
Entered number is 4938
It takes the 8 adds it to sum
Divides by ten giving 493
Takes the 3 subtracts it from sum: sum = 5
Divides by ten giving 49
Takes 9 and adds it to sum: sum = 14
Divides by ten giving 4
Takes 4 subtracts it from sum: sum = 10
THEN it checks if this is divisible by 11.
Ok, I know why now. He/she's trying to teach you something besides computing about numbers
I suspect it is simulating the manual test that digits in the odd positions and the digits in the even positions differ by a factor of 11. In practice using %11 would be the way to go.
EDIT: If the example were truly trying to avoid doing % 11, it should send the sum through again until it is 0.
It an example to show how to implement that particular check. Using your example would not demonstrate the same code methodologies.