convert decimal to binary - java

Code is mostly done but my code is printing incorrectly its printing out as 110 as opposed to 011. The problem im doing requires to reverse the "110" to "011"
import java.util.Scanner;
public class LabProgram {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int num, binaryNum = 0;
int i = 1, rem;
num = scan.nextInt();
while (num != 0)
{
rem = num % 2;
num /= 2;
binaryNum += rem * i;
i *= 10;
}
System.out.println(binaryNum);
}
}

Then use a string as follows:
int num = scan.nextInt();
String s = "";
while (num != 0) {
int rem = num % 2;
num /= 2;
s = s + rem; // this concatenates the digit to the string in reverse order.
// if you want it in normal order, do it -> s = rem + s;
}
System.out.println(s);

You may directly print each binary digit without storing it in binaryNum
while (num != 0) {
System.out.print(num % 2);
num /= 2;
}
System.out.println();

You can simply use Integer#toBinaryString(int) to return the result as a binary string.
Scanner scan = new Scanner(System.in);
int value = scan.nextInt();
System.out.println(Integer.toBinaryString(value));

Related

"if" condition problem in java Armstrong code

I wrote the armstrong number question in java by myself(sorry if its silly, I'm new to programming).
The "result is supposed to give 1 value when i enter a coorect armstrong number but it gives 0,why?
Code-
import java.util.Scanner;
public class Exercise1_4 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int result = 0;
int i = 0;
int sum = 0;
while (n > 0) {
i = n % 10;
sum += i * i * i;
n = n / 10;
}
if (sum == n) {
System.out.print("1");
} else {
System.out.print("0");
}
n is changed in the while loop. After the while loop n == 0 (if n was entered as a non-negative number). This the only case where sum == n is true will be sum == 0. You need to introduce a temporary variable which is modified in the loop and keep n unchanged.
int temp = n;
while (temp > 0) {
int i = temp % 10;
sum += i * i * i;
temp /= 10;
}
N.B. result is not used, i not decalred inside the while loop

Product of digits

public class ProductOfDigits {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter an integer: ");
int n = input.nextInt();
int x = Math.abs(n);
int product = 1;
if (x >=0 && x<=9) {
System.out.println(x);
}
else {
product = product * (x % 10);
x = x/10;
System.out.println(product);
}
When the input is negative number, the product is between first and last digit. Can anyone explain? I have tried Math.abs() to get absolute value but it is impossible and it is killing me now.
Do it as follows:
import java.util.Scanner;
public class ProductOfDigits {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter an integer: ");
int n = input.nextInt();
int x = Math.abs(n);
int รง = 1;
int product = 1;
if (x == 0) {
product = 0;
} else {
while (x > 0) {
product *= x % 10;
x /= 10;
}
}
System.out.println(product);
}
}
Sample run-1:
Enter an integer: -256
60
Sample run-2:
Enter an integer: 0
0
Sample run-3:
Enter an integer: 9
9
Sample run-4:
Enter an integer: 256
60
Recursive version:
import java.util.Scanner;
public class ProductOfDigits {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter an integer: ");
int n = input.nextInt();
System.out.println(productOfDigits(n));
}
static int productOfDigits(int n) {
n = Math.abs(n);
if (n > 0 && n < 10) {
return n;
}
if (n == 0) {
return 0;
}
return (n % 10) * productOfDigits(n / 10);
}
}
You can use Math.log10() function from java to get the number of your digits and then calculate the first digit based on it:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter an integer: ");
int number = input.nextInt();
if (number < 0) {
number *= (-1);
}
int digits = (int) Math.log10(number);
int lastDigit = number % 10;
int firstDigit = (int) (number / Math.pow(10, digits));
int product = lastDigit * firstDigit;
System.out.println(product);
}
And of course, if your number is negative, you can use Math.abs() (instead of if)
Your current code only prints out the last digit of the entered integer because you are only doing product = product * (x % 10); (can be simplified to product *= x % 10;) and x = x / 10; (can be simplified to x /= 10;) once each. You should repeatedly do these two operations until x is 0.
You could use a for loop or a while loop for this. Here's how to write this with a for loop:
for (; x > 0 ; x /= 10) {
product *= x % 10;
}
The condition for the if statement can also be changed to just x == 0, as the x values 1-9 can all be correctly handled by the else clause.

Armstrong number checking in Java

I'm trying to write a class which checks if a number is an Armstrong number or not. I'm having trouble with the following block of code.
public boolean checkNum(long num) {
digits = (int) (Math.log10(num) + 1);
String number = String.valueOf(num);
numDigits = number.toCharArray();
for (int i = 0; i < numDigits.length; i++) {
digit = numDigits[i] * 1.0;
power = digits * 1.0;
sum = sum + (long) (Math.pow(digit, power));
}
if (sum == num) {
return true;
} else {
return false;
}
}
The casting doesn't seem to work, and checkNum returns false every time. Is this a correct method, and are there any better ways of doing this?
Try this, using only arithmetic operations and it works for non-negative integers with an arbitrary number of digits (as long as they fit into a long).
public boolean checkNum(long num) {
long n = num;
long sum = 0;
// find the number of digits
int power = (int) Math.floor(Math.log10(n == 0 ? 1 : n)) + 1;
while (n != 0) {
int digit = (int) n % 10;
sum += Math.pow(digit, power);
n /= 10;
}
return sum == num;
}
Alternatively (albeit less efficiently) you could transform the number into a string and iterate over each of the characters converting them into digits. Here's a fixed version of your intended solution, with comments on the key points:
public boolean checkNum(long num) {
String number = String.valueOf(num);
char[] numDigits = number.toCharArray();
long sum = 0;
// a simple way to obtain the number of digits
int power = numDigits.length;
for (int i = 0; i < numDigits.length; i++) {
// this is how we transform a character into a digit
int digit = Character.digit(numDigits[i], 10);
// we need to rise digit to the value of power
sum = sum + (long) Math.pow(digit, power);
}
if (sum == num) {
return true;
} else {
return false;
}
}
For example, use either implementation to verify that the following are Armstrong numbers:
checkNum(6)
=> true
checkNum(371)
=> true
checkNum(1634)
=> true
You can also use this simple logic
public class Armstrong {
public static void main(String[] args) {
int number = 371, originalNumber, remainder, result = 0;
originalNumber = number;
while (originalNumber != 0)
{
remainder = originalNumber % 10;
result += Math.pow(remainder, 3);
originalNumber /= 10;
}
if(result == number)
System.out.println(number + " is an Armstrong number.");
else
System.out.println(number + " is not an Armstrong number.");
}
}
Guess This will work:
boolean isArmstrong(int x){
int s=0;
int u=x;
while(x!=0)
{
int y=x%10;
s=s+(y*y*y);
x=x/10;
}
if(u==s)
return true;
else
return false;
}
How to Check Number is Armstrong or Not
public boolean isArmstrongNum(int input)
{
int sum=0,rem,temp;
temp=input;
while(input>0)
{
rem=input%10;
input=input/10;
sum=sum+(rem*rem*rem);
}
return sum==temp;
}
In Kotlin, you can use:
fun main() {
println("---------------------------------------")
val userInputValues = Scanner(System.`in`)
//* Kotlin Program to Display Armstrong Numbers Between Intervals Using Function
println("* Kotlin Program to Display Armstrong Numbers Between Intervals Using Function\n")
println("Enter your number range")
println("Enter start number of your range \t ")
val startRange = userInputValues.nextInt()
println("Enter end number of your range \t ")
val endRange = userInputValues.nextInt()
println("\n\n------ Armstrong number between $startRange and $endRange ------ ")
for (number in startRange..endRange) {
var stringNumber : String = number.toString()
var numberArray = stringNumber.toCharArray()
var powerOfNumber:Int = numberArray.size;
var result = 0
for (digit in numberArray){
var intDigit:Int = digit.toString().toInt()
result += intDigit.toDouble().pow(powerOfNumber.toDouble()).toInt()
}
if(result == number){
println( "$number is Armstrong number")
}
}
println("---------------------------------------")
}
public static void main(String[] args) {
Scanner scanner=new Scanner(System.in);
System.out.print("Enter the number: ");
int number=scanner.nextInt();
scanner.close();
int lastDigit=0;
int reverseNum=0;
int originalNumber=number;
while(originalNumber!=0) {
lastDigit=originalNumber%10;
reverseNum +=(lastDigit*lastDigit*lastDigit);
originalNumber /=10;
}
if(reverseNum==number) {
System.out.println("Number is Armstrong");
}
else {
System.out.println("Number is not Armstrong");
}
}
This image is testing image of this code in terminal.
The best way is using while loop.
Here is your Answer for finding 3 digits Armstrong numbers.
import java.util.Scanner;
class Main {
////////////////////////////////////////////
////////////////////////////////////////////
public static void main(String args[])
{
System.out.println("Hello world!");
Scanner sc = new Scanner(System.in);
int num = sc.nextInt();
int numc = num;
int rem = 0;
int cu = 0;
int val = 0;
while(num != 0){
rem = num%10;
cu = rem*rem*rem;
val += cu;
num /= 10;
}
if(val == numc){
System.out.println("Yes its a Armstrong number ");
}else{
System.out.println("No its not a Armstrong number ");
}
}
}
///////////////////////////////////////////
Here I have done a code to find armstrong number dynamically:
import java.util.Scanner;
public class Armstrong {
public static void main(String[] args) {
if(isArmstrongNumber(input())) {
System.out.println("armstrong number");
} else {
System.out.println("Not armstrong number");
}
}
private static int input() {
try(Scanner reader = new Scanner(System.in)) {
return reader.nextInt();
}
}
private static int digitCount(int num) {
int count = 0;
while(num > 0) {
num = num / 10;
count++;
}
System.out.println("No of digit : " + count);
return count;
}
private static int power(int num, int count) {
int sum = 0;
while(num > 0) {
int result = 1;
int r2 = num % 10;
num /= 10;
for(int digit = count; digit > 0; digit--) {
result *= r2;
}
sum += result;
}
System.out.println("Sum : " + sum);
return sum;
}
public static boolean isArmstrongNumber(int num) {
int count = digitCount(num);
int sum = power(num, count);
return sum == num;
}
}
Here is the result:
371
No of digit : 3
Sum : 371
armstrong number
Hope this code helps you better.

return a variable to pass to another method

I have been working on this project for a week, and can not figure out what I have done wrong. It is supposed to accept a five digit number, then separate the number with three spaces between each number. So far all it does is not work, then spit out a line of red expletives basically saying that it doesn't work.
Can anyone point me in the right direction?
import java.util.*;
public class program1
{
static Scanner input = new Scanner (System.in);
public static void main (String [] args)
{
// variables and stuff
int num = 00000;
getnum();
separate_number(num);
}
// methods are here
public static void getnum()
{
int num;
do{
System.out.println("Please enter a five digit number");
num = input.nextInt();
if (num < 10000 || num > 99999)
{
System.out.println("The number is not five digits");
}
}while (num < 10000 || num > 99999);
}
public static int separate_number(int num)
{
int digit5, digit4, digit3, digit2, digit1;
digit5 = num % 10;
num = num / 10;
digit4 = num % 10;
num = num / 10;
digit3 = num % 10;
num = num / 10;
digit2 = num % 10;
num = num / 10;
digit1 = num % 10;
num = num / 10;
return Integer.parseInt(+ digit1 + " " + digit2 + " " + digit3 + " " + digit4 + " " + digit5);
}
}
You had several problems:
getnum does not do anything. While it does get input from the user, it never does anything with it, so isn't actually helpful. Instead, you should make it return an int, which you'll store in a variable in name.
Integer.parseInt is meant to accept a string as input, and try and convert it into an integer. It will throw an error if you try feeding it an invalid number. 1 2 3 4 5 is never going to be a number, so that's why your program isn't working. In any case, you want to go the other way around -- you want to convert a number into a String.
You never do anything with the string you return from separate_number.
Taken all together, a corrected version of your code might look like this:
import java.util.*;
public class program1
{
static Scanner input = new Scanner (System.in);
public static void main (String [] args) {
int num = getnum();
System.out.println(separate_number(num));
}
public static int getnum() {
int num;
do {
System.out.println("Please enter a five digit number");
num = input.nextInt();
if (num < 10000 || num > 99999) {
System.out.println("The number is not five digits");
}
} while (num < 10000 || num > 99999);
return num;
}
public static String separate_number(int num) {
int digit5, digit4, digit3, digit2, digit1;
digit5 = num % 10;
num = num / 10;
digit4 = num % 10;
num = num / 10;
digit3 = num % 10;
num = num / 10;
digit2 = num % 10;
num = num / 10;
digit1 = num % 10;
num = num / 10;
return digit1 + " " + digit2 + " " + digit3 + " " + digit4 + " " + digit5;
}
}
You can simply extract the digits of an integer in java like this and do whatever you want with them:
public static void getnum()
{
int num;
do{
System.out.println("Please enter a five digit number");
num = input.nextInt();
if (num < 10000 || num > 99999)
{
System.out.println("The number is not five digits");
}
}while (num < 10000 || num > 99999);
}
public static int separate_number(int num)
{
String numStr = num +"";
String[] digits = numStr.split("");
String separatedDigits = "";
for (String s: digits) {
separatedDigits += s + " ";
System.out.println(s);
}
// you can return separatedDigits just change the type of the method to String
return Integer.parseInt(numStr);//Very nonesense!
}
The function parseInt parses a string that is a number.
Integer.parseInt(+ digit1 + " " + digit2 + " " + digit3 + " " + digit4 + " " + digit5)
No matter what your digits are, "# # # # #" is not a number.
Also, you have an extra plus-sign at the beginning which, although legal, is useless. It just declares that the first digit is positive.
To separate a number into pieces, convert it to a string
(new Integer(theNumber)).toString()
and manually split the string, use String.format(s,o...), or, probably best of all:
System.out.println(NumberFormat.getNumberInstance(Locale.US).format(35634646));
Output: 35,634,646
From this answer

Converting decimal to binary error

I wanted to convert decimal to binary and the following code doesn't work.
Please help me to correct the code.
package mainpackage;
import java.util.*;
class MainClass {
public MainClass() {
}
public static int binaryfinder(int n) {
int a[] = new int[8];
int i = 0;
int b = 0;
int n1 = n;
while (n1 > 0) {
a[i] = n1 % 2;
i++;
n1 = n1 / 2;
}
System.out.printf("Binary number of %d is = ", n);
for (int j = i - 1; j >= 0; j--) {
b += ((10 ^ j) * a[j]);
}
return b;
}
public static void main(String[] args) {
System.out.println("\nEnter the number to find its binary value:\n");
Scanner k = new Scanner(System.in);
int num = k.nextInt();
int inBin = binaryfinder(num);
System.out.print(inBin);
}
}
After I click RUN, it asks to enter the binary value and when I enter the value, it says, "Binary number of 0 = " No matter what I enter it always outputs "Binary number of 0 = ".
No errors are thrown.
Integer.toBinaryString(i)
this should do the trick in java
You have an endless loop, thats why your program never terminates:
while (j != 0) {
b += ((10 ^ j) * a[j]);
}
After I click RUN, it asks to enter the binary value and when I enter the value, it says, "Binary number of 0 = " No matter what I enter it always outputs "Binary number of 0 = ". No errors are thrown.
Never ending while loop
while (j != 0) {
b += ((10 ^ j) * a[j]);
}
You are changing value of n and finally after while loop :n = 0 and so the output
while (n > 0) {
a[i] = n % 2;
i++;
n = n / 2;
}
System.out.println(output);
Your program (as whole) is incorrect
Other Options:
1) Use Integer.toBinaryString()
2) Use the basic formula to convert decimal --> binary
int n = 10;
String output = "";
do {
output = (n % 2) + output; // reverse string
n = n / 2;
} while (n > 0);

Categories

Resources