Need Explaination : Adding Two Binary Numbers in Java - java

Can anyone please explain this code?
Programme: How to add two binary number.
explain below the asterix sign
import java.util.Scanner;
public class Exercise17 {
public static void main(String[] args)
{
long binary1, binary2;
int i = 0, remainder = 0;
int[] sum = new int[20];
Scanner in = new Scanner(System.in);
System.out.print("Input first binary number: ");
binary1 = in.nextLong();
System.out.print("Input second binary number: ");
binary2 = in.nextLong();
while (binary1 != 0 || binary2 != 0)
{
// explain code below
// what does %10 means?
// why %2?
sum[i++] = (int)((binary1 % 10 + binary2 % 10 + remainder) % 2);
remainder = (int)((binary1 % 10 + binary2 % 10 + remainder) / 2);
binary1 = binary1 / 10;
// why to divide by /10?
binary2 = binary2 / 10;
}
if (remainder != 0) {
sum[i++] = remainder;
}
--i;
System.out.print("Sum of two binary numbers: ");
while (i >= 0) {
System.out.print(sum[i--]);
}
System.out.print("\n");
}
}

%10 means remainder of division by 10.
%2 is remainder of division by 2.
/ 10 is basically shift by one digit.
Imagine you have two "binary" numbers 101 and 110. %10 will get you the last digit for each of the numbers (1 and 0). Then you sum these digits and %2 gets you the digit of the sum.
The best way to understand the code is to run it in a debugger.

Related

How to break the execution of the code based on a user input

So I am doing a digit counter thing basically
I want it to display 123 and which number is what place value for example 123
------------------------------------
Enter any number: 123
Ones: 3
Tens: 2
Hundreds: 1
------------------------------------
this is my code
import java.util.Scanner;
public class digits {
public static void main(String[] args)
{
Scanner scann = new Scanner(System.in);
System.out.print("Enter any number: ");
int number = scann.nextInt();
int num1 = number % 10;
int num2 = number / 10 % 10;
int num3 = number / 100 % 10;
int num4 = number / 1000 % 10;
int num5 = number / 10000 % 10;
int num6 = number / 100000 % 10;
int num7 = number / 1000000 % 10;
int num8 = number / 10000000 % 10;
scann.close();
System.out.println("Ones: "+num1);
System.out.println("Tens: "+num2);
System.out.println("Hundreds: "+num3);
System.out.println("Thousands: "+num4);
System.out.println("Ten-Thousands: "+num5);
System.out.println("Hundred-Thousands: "+num6);
System.out.println("Millions: "+num7);
System.out.println("Ten-Millions: "+num8);
}
}
How do I stop it from printing the rest if I only type 123?
Output I got
--------------------------
Enter any number: 123
Ones: 3
Tens: 2
Hundreds: 1
Thousands: 0
Ten-Thousands: 0
Hundred-Thousands: 0
Millions: 0
Ten-Millions: 0
------------------------
Output I want
--------------------------
Enter any number: 123
Ones: 3
Tens: 2
Hundreds: 1
------------------------
You need to introduce a condition (or conditions) in your code.
You can achieve that with a chain of if statements. But the better way to do it is by utilizing a loop. Because that will allow you to get rid of the intermediate variables (num1, num2, etc) and to avoid duplicating the line of code that prints the remainder on the consol. That will make the code more readable and concise.
In order to be able to apply the loop for this problem, you need to create an array of strings that will store all quantifiers ("Ones: ", "Tens: ", etc).
It can be done like that:
public static final String[] quantifiers =
{"Ones: ", "Tens: ", "Hundreds: ", "Thousands: ",
"Ten-Thousands: ", "Hundred-Thousands: ", "Millions: ", "Ten-Millions: "};
public static void main(String[] args) {
Scanner scann = new Scanner(System.in);
int number = scann.nextInt();
for (int i = 0; i < quantifiers.length && number > 0; i++) {
System.out.println(quantifiers[i] + number % 10);
number /= 10; // does the same as number = number / 10;
}
}
output for input 123
Ones: 3
Tens: 2
Hundreds: 1
It might help your question. Because of hardcoded terms such as 'tens' or 'hundreds', it is not generic enough.
public static void main(String[] args) {
Scanner scann = new Scanner(System.in);
System.out.print("Enter any number: ");
int number = scann.nextInt();
int length = String.valueOf(number).length();
for(int i=0; i< length; i++){
if(i == 0){
System.out.println("Ones: "+ number % 10);
}else if(i == 1)
System.out.println("Tens: " + number / 10 % 10);
else if(i == 2)
System.out.println("Hundreds: "+ number / 100 % 10);
else if(i == 3)
System.out.println("Thousands: "+ number / 1000 % 10);
else if(i == 4)
System.out.println("Ten-Thousands: "+ number / 10000 % 10);
else if(i == 5)
System.out.println("Hundred-Thousands: "+ number / 100000 % 10);
else if(i == 6)
System.out.println("Millions: "+ number / 1000000 % 10);
else if(i == 7)
System.out.println("Ten-Millions: " + number / 10000000 % 10);
}
scann.close();
}
Your code is printing all the numbers because that's what you wrote:
System.out.println("Ones: "+num1);
...and so on.
If you never want to print e.g. thousands, just remove the println for thousands. If you only want to print them if someone actually enters thousands, add an if statement:
if (num4 > 0) {
System.out.println("Thousands: "+num4);
}
Repeat for the others.

How does this program to calculate Armstrong numbers between two intervals work step by step?

class Armstrong {
public static void main(String[] args) {
int low = 999, high = 99999;
for(int number = low + 1; number < high; ++number) {
int digits = 0;
int result = 0;
int originalNumber = number;
// number of digits calculation
while (originalNumber != 0) {
originalNumber /= 10;
++digits;
}
originalNumber = number;
// result contains sum of nth power of its digits
while (originalNumber != 0) {
int remainder = originalNumber % 10;
result += Math.pow(remainder, digits);
originalNumber /= 10;
}
if (result == number)
System.out.print(number + " ");
}
}
How does this program work? It would be very helpful. Program to find Armstrong between two intervals? Can someone explain step by step? Help me out.
Steb-by-step Explanantion
Initialize the start and end of the interval with 999 and 9999
You can change these numbers but ensure that low is always lesser than high:
int low = 999;
int high = 99999;
for (int number = low + 1; // Create a variable number and assign it one number greater than low
number < high; // This loop should keep repeating until number is less than high(end of the interval)
++number // After each repetition, increment the value of number by 1
) {
Create a variable digits to store the number of digits in number.
For example, if number is 100, this will be later set as 3 as the algorithm proceeds:
int digits = 0;
Create a variable result that will store the sum of powers of numbers:
int result = 0;
Copy the value of number to a local variable originalNumber because it has to be modified:
int originalNumber = number;
The logic of calculating number of digits in a number is keep dividing it by 10 until the number is 0.
Every time you divide any number by 10, the last digit is stripped out. So every time the last digit is stripped out, increment digit by 1 (digit++)
// number of digits calculation
while (originalNumber != 0) // Continue this while loop till originalNumber is not 0
{
originalNumber /= 10; // Divide the number by 10. Dividing a number by 10 removes its last digit.
++digits; // One digit was removed in the above step, which means it has to be counted, so increment digit by 1
}
// For example, for originalNumber = 423,
// 423 / 10 = 42 : digits = 1 (first loop)
// 42 / 10 = 4 : digits = 2 (second loop)
// 4 / 10 = 0 : digits = 3 (third loop)
// Now originalNumber has become 0, so the while loop condition originalNumber != 0 will be false and the loop will stop.
// Now we have digits = 3, which is the number of digits in 423
// When program reaches here, digits will have the number of digits in the
// number "originalNumber"
Copy number again to originalNumber because we want to modify the number
again and originalNumber has become 0 because of the digit counting loop above:
originalNumber = number;
An Armstrong number is a number which is equal to the sum of digits to the power of its number of digits.
e.g.: in 153, (1^3) + (5^3) + (3^3) = 153. We are obtaining the cube of each digit(1, 5, 3) because 153 has 3 digits 1, 5, 3.
If it was say 50, we would check ( 5^2 + 0^2) because 50 has 2 digits (50 is not Armstrong, because 25 + 0 = 25 which is not equal to 50)
We saw above dividing a number by 10 removes the last digit (423 / 10 = 42)
Similarly, if we only want this last digit, we can get it by modulus 10 (% 10): (423 % 10 = 3) (42 % 10 = 2) (4 % 10 = 4)
// Let's assume originalNumber is 153
while (originalNumber != 0) // Same as above, keep looping till the originalNumber is not 0(i.e. all digits have been removed)
{
Extract the last digit to remainder, (for 153: 153 % 10 = 3) (for 15: 15 % 10 = 5)
int remainder = originalNumber % 10;
Now we have the last digit, we need to raise this digit to the number of
digits i.e. 3(for 153): (3^3) = 27. We do this using Math.pow(3, 3). Add this number to result. In the end after each loop's number's power is added, at the end of the loop, result will contain their sum:
result += Math.pow(remainder, digits);
originalNumber /= 10; // Remove the last digit (same as above, for 153: 153 / 10 = 15)
// After this line finishes, one rightmost digit will be removed, this will keep
// happening till originalNumber = 153 becomes 15, then 1, then 0.
// When originalNumber is 0, loop stops and we will have the total sum in result
}
For an Armstrong number like 153, result will also contain 153. For a non-Armstrong number it will contain something else.
if (result == number) // For 153, both will be equal.
System.out.print(number + " "); // This will only execute if result is equal to number, or in other words, only if the number is Armstrong
}
Improvements
As per single responsibility principle, each function or class must exactly do one thing. You have a monolithic main() method that:
Defines the interval
Counts the digit of each number in the interval
Calculate the sum of powers of digits
Check if number is Armstrong and print it.
I would prefer breaking down each operation to a separate method, so that it improves readability and maintainability while respecting single-responsibiliy principle:
class Armstrong {
public static int countDigits(int number) {
int digits = 0;
while (number != 0) {
number /= 10;
++digits;
}
return digits;
}
public static int digitPowerSum(int number, int power) {
int result = 0;
while (number != 0) {
int remainder = number % 10;
result += Math.pow(remainder, power);
number /= 10;
}
return result;
}
public static boolean isArmstrong(int number) {
int digits = countDigits(number);
int sum = digitPowerSum(number, digits);
return sum == number ; // will return true if both numbers are equal else false
}
public static ArrayList<Integer> armstrongNumbersBetween(int low, int high) {
ArrayList<Integer> numbers = new ArrayList<>();
for(int number = low + 1; number < high; number++) {
if (isArmstrong(number)) {
numbers.add(number);
}
}
return numbers;
}
public static void main(String[] args) {
int low = 999, high = 99999;
ArrayList<Integer> numbers = armstrongNumbersBetween(low, high);
for(int number : numbers) {
System.out.print(number + " ");
}
}
}
Here, each method does exactly one thing and this helps in better reusability. You just have to call the required methods to perform a specific operation.
If something is unclear, let me know.

How to reverse the order of an int without turning it into a string

I have been tasked with the assignment of creating a method that will take the 3 digit int input by the user and output its reverse (123 - 321). I am not allowed to convert the int to a string or I will lose points, I also am not allowed to print anywhere other than main.
public class Lab01
{
public int sumTheDigits(int num)
{
int sum = 0;
while(num > 0)
{
sum = sum + num % 10;
num = num/10;
}
return sum;
}
public int reverseTheOrder(int reverse)
{
return reverse;
}
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
Lab01 lab = new Lab01();
System.out.println("Enter a three digit number: ");
int theNum = input.nextInt();
int theSum = lab.sumTheDigits(theNum);
int theReverse = lab.reverseTheOrder(theSum);
System.out.println("The sum of the digits of " + theNum + " is " + theSum);
}
You need to use the following.
% the remainder operator
/ the division operator
* multiplication.
+ addition
Say you have a number 987
n = 987
r = n % 10 = 7 remainder when dividing by 10
n = n/10 = 98 integer division
Now repeat with n until n = 0, keeping track of r.
Once you understand this you can experiment (perhaps on paper first) to see how
to put them back in reverse order (using the last two operators). But remember that numbers ending in 0 like 980 will become 89 since leading 0's are dropped.
You can use below method to calculate reverse of a number.
public int reverseTheOrder(int reverse){
int result = 0;
while(reverse != 0){
int rem = reverse%10;
result = (result *10) + rem;
reverse /= 10;
}
return result;
}

Java Split Number into Digit's Algorithm

package test;
import java.util.Scanner;
public class SplitNumber
{
public static void main(String[] args)
{
int num, temp, factor = 1;
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number: ");
num = sc.nextInt();
temp = num;
while (temp != 0) {
temp = temp / 10;
factor = factor * 10;
}
System.out.print("Each digits of given number are: ");
while (factor > 1) {
factor = factor / 10;
System.out.print((num / factor) + " ");
num = num % factor;
}
}
}
I can't understand this int factor's job. Can someone help me to understand this codes algorithm?
In programming languages, if you hold double value in the int,it rounds the number to lower one thus if you do 15/10 it will return 1 as int and if you do 5/10 it will return 0. With this knowledge you can understand.
For example,let the number be 953,
while (temp != 0) {
temp = temp / 10;
factor = factor * 10;
}
1.Iteration temp = 95 , factor = 10
2.Iteration temp = 9 , factor = 100
3.Iteration temp = 0 , factor = 1000
end of while loop because temp is 0.
while (factor > 1) {
factor = factor / 10;
System.out.print((num / factor) + " ");
num = num % factor;
}
1.Iteration num = 953 factor = 100 , 953/100 = 9 (you get first digit)
2.Iteration num = 953%100 = 53 , factor = 10 , 53/10 = 5 (you get second digit)
3.Iteration num = 53%10 = 3 , factor = 1 , 3/1 = 3 (you get last digit)
End of while loop.
Actually it is basic math. When you want to extract nth digit of number, you just have to divide it by 10^n.
The modulus operator to extract the rightmost digit or digits from a number. For example, x % 10 yields the rightmost digit of x (in base 10). Similarly x % 100 yields the last two digits.
Here more info
If you would not care about flipping the order of digits, you could simply write
int num = sc.nextInt();
do {
System.out.println(num % 10);
num = num / 10;
} while(num != 0);
The modulo operation num % 10 calculates the remainder of dividing num by 10, effectively gets the digit at the lowest position ("ones"). 0 % 10 is 0 ... 9 % 10 is 9, 10 % 10 is 0 again, and so on. Then the division by 10 makes the old "tens" the new "ones", and the entire thing is repeated until 0 remains.
The hassle in your code is about emitting the digits in the "correct" order, highest position first, ones last. So it first checks how many digits are in your number, factor grows to the same size in the process. temp=temp/10; has the same role as num=num/10; in the short snippet (cutting a digit from the number in each iteration), and factor=factor*10 "adds" a digit to factor at the same time. [I just stop here as there is an accepted answer already explaining this]

Java: How to test if individual characters are even or odd? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 8 years ago.
Improve this question
In Java, how do I test if a character is an even or odd digit?
Here is what I have so far:
import java.util.Scanner;
public class OddOrEven{
public static void main(String args[]){
Scanner input = new Scanner(System.in);
int number, digit1, digit2, digit3;
System.out.print( "Enter three-digit number: " );// prompt
number = input.nextInt(); // read number
// determine the 3 digits
digit1 = number / 100;
digit2 = number % 100 / 10;
digit3 = number % 100 % 10;
if (digit1 % 2 == 0 && digit2 % 2 == 0 && digit3 % 2 == 0);
System.out.println( "This number contains all even digits.");
if (digit1 % 2 != 0 && digit2 % 2 == 0 && digit3 % 2 == 0);
System.out.println("This number contains both odd and even digits.");
if (digit1 % 2 != 0 && digit2 % 2 != 0 && digit3 % 2 == 0 );
System.out.println("This number contains both odd and even digits.");
if (digit1 % 2 == 0 && digit2 % 2 != 0 && digit3 % 2 == 0 );
System.out.println("This number contains both odd and even digits.");
if (digit1 % 2 == 0 && digit2 % 2 != 0 && digit3 % 2 != 0);
System.out.println("This number contains both odd and even digits.");
if (digit1 % 2 != 0 && digit2 % 2 != 0 && digit3 % 2 != 0);
System.out.println("This number contains all odd digits.");
}
}
If the number you are working with is an int (or a similar primitive type like long) then you can do something like this
int num = // something
while (num != 0) {
int digit = num % 10;
System.out.println(digit + " is " + (digit % 2 == 0 ? "even" : "odd"));
num /= 10;
}
This will iterate over the digits from right to left.
public static void main(String[] args) throws Exception {
int num = 28172;
String temp = Integer.toString(num);
int[] numArray = new int[temp.length()];
for (int i = 0; i < temp.length(); i++) {
numArray[i] = temp.charAt(i) - '0';
}
for (int i : numArray) {
System.out.println("Num " + i + " is " + ((i % 2 == 0) ? "even" : "odd"));
}
}
Gives me the output:
Num 2 is even
Num 8 is even
Num 1 is odd
Num 7 is odd
Num 2 is even
First, convert the int to a String. Then, since Strings are Character arrays, you can loop through each character in the array and turn it into an Integer by subtracting the ascii Character 0. Then, you can loop through each Integer in this array, and use the mod operator (%) which will give you the remainder of a division. num%2==0 will return true if the number is even, otherwise false.

Categories

Resources