I am having trouble getting this method, which converts an integer from binary to decimal, to work properly. The main problem I have found is that with binary numbers that end in 0, the last 0 is ignored by the program. For example, if I input 1010, the program would return 5 instead of 10. Below is my method for this conversion.
public int toDecimal(int inBase2){
int num = 0;
if(inBase2 < 0){
num = -1;
return num;
}
if(inBase2 == 0 && num == 0){
return num;
}else{
num = inBase2 % 10 * (int)(Math.pow(2, Math.log10(inBase2)));
return num + toDecimal(inBase2 / 10);
}
}
How would I go about fixing the program in a way that allows it to read the final 0 in the binary integer correctly?
You're doing the calculation the wrong way round. The least significant digit in the binary number is treated as though it's the most significant. So effectively, 1010 returns the result for 0101. Right now, the first digit you process, in the ones place, is multiplied by Math.pow(2, Math.log10(inBase2)), and given the most weight. Instead, you should multiply the results of the recursive function, so later calls (which represent higher value digits) are multiplied more. Example
public int toDecimal(int inBase2){
int num = 0;
if(inBase2 < 0){
num = -1;
return num;
}
if(inBase2 == 0 && num == 0){
return num;
}else{
num = inBase2 % 10;
return num + 2 * toDecimal(inBase2 / 10);
}
}
Related
This question already has answers here:
Java reverse an int value without using array
(33 answers)
Closed 3 years ago.
I'm a Java beginner so please pardon me if the question seems silly but I already searched the forums but it seems like no one has my problem.
I need to reverse the digits of an integer, and my class hasn't covered while or if loops yet, so I can't use those. All answers I can find on stackoverflow use those, so I can't use those.
the input I am given is below 10000 and above 0 and the code I have written has no problem reversing the integer if the input is 4 digits (e.g. 1000 - 9999) but once the input is between 1 - 999 it creates zeroes on the right hand side but according to the answer sheets its wrong.
For example: 1534 gets turned into 4351, but
403 becomes 3040 instead of the 304 it should be, and 4 becomes 4000 instead of 4.
I've tried different things in the code but it seems to just keep giving the same answer. Or maybe I'm just missing some key mathematics, I'm not sure.
Scanner scan = new Scanner(System.in);
System.out.println ("Enter an integer:");
int value = scan.nextInt();
int digit = (value % 10);
value = (value / 10);
int digit2 = (value % 10);
value = (value / 10);
int digit3 = (value % 10);
value = (value / 10);
int digit4 = (value % 10);
String reversednum = ("" + digit + digit2 + digit3 + digit4);
System.out.println ( reversednum);
and
Scanner scan = new Scanner(System.in);
System.out.println ("Enter an integer:");
int value = scan.nextInt();
int digit = (value % 10);
int reversednum = (digit);
value = (value /10);
digit = (value % 10);
reversednum = (reversednum * 10 + digit);
value = (value / 10);
digit = (value % 10);
reversednum = (reversednum * 10 + digit);
value = (value / 10);
digit = (value);
reversednum = (reversednum * 10 + digit);
System.out.println (reversednum);
What am I doing wrong?
You can convert from int to String -> reverse String -> convert again in int.
This is a code example.
public int getReverseInt(int value) {
String revertedStr = new StringBuilder(value).reverse().toString();
return Integer.parseInt(revertedStr);
}
Your code assumes that the number can be divided by 1000, which is clearly not the case for numbers below 1000. So add some if statements:
public int reverseNumber(int n) {
// step one: we find the factors using integer maths
int s = n;
int thousands = s / 1000; // this will be 0 if the number is <1000
s = s - thousands*1000;
int hundreds = s / 100; // this will be 0 if the number is <100
s = s - hundreds*100;
int tens = s / 10; // etc.
s = s - tens*10;
int ones = s;
// then: let's start reversing. single digit?
if (n<10) return n;
// two digits?
if (n<100) {
return ones*10 + tens;
}
// etc.
if (n<1000) {
return ones*100 + tens*10 + hundreds;
}
if (n<10000) {
return ones*1000 + tens*100 + hundreds*10 + thousands;
}
// if we get here, we have no idea what to do with this number.
return n;
}
Without spoon-feeding you code (leaving the value of writing your own homework code intact)...
Although you've said you can't use a loop, I don't think there's a sane approach that doesn't use one. Your basic problem is you have hard-coded a solution that works when the number happens to have 4 digits, rather than using code that adapts to a variable length. ie, are not using a loop.
All is not lost with your code however. You have figured out the essence of the solution. You just need to convert it to work processing one digit at a time. Consider using recursion, that divides the number by 10 each time and continues until the number is zero. Of course, you’ll have to capture the end digit before it’s lost by division.
Pseudo code may look like:
pass in the number and the current result
if the number is 0 return result
multiply result by 10 and add remainder of number divided by 10
return the result of calling self with number divided by 10 and result
then call this passing number and zero
Using modulus and division:
int nbr = 123; // reverse to 321 or 3*10*10 + 2*10 + 1
int rev = 0;
while(nbr > 0) {
rev *= 10; // shift left 1 digit
int temp = nbr % 10; // get LO digit
rev += temp; // add in next digit
nbr /= 10; // move to next digit
}
Or a recursive method:
public static int reverseInt(int number, int value) {
switch(number) { // is this conditional statement allowed???
case 0:
return value;
}
value *= 10;
int lod = number % 10;
value += lod;
number /= 10;
return reverseInt(number, value);
}
I'm a novice Java coder working on a problem dealing with counting consecutive integers in the binary forms of numbers.
The numbers are read from the input, and converted to binary using the method called conversion. The binary form is then sent to a character array where the for loop checks for consecutive characters(specifically the number 1) and prints the maximum count as the final answer.
I've managed to get the code to a state where I feel it should be working, but I've only had success with about half of the test cases. The larger number conversions like 262,141 tend to produce incorrect answers. Can anyone tell me where I've gone wrong?
I have a suspicion that it's something to do with the character array, but after several hours of research I haven't been able to find a solution to my particular problem.
import java.io.*;
import java.util.*;
public class Solution {
public static int conversion(int decimal){//this will take the decimal from the input and convert it to binary
int result = 0;//the result from each step of the conversion
int base = 1;//used to multiply the remainder by 1, 10, 100 etc
while(decimal > 0){
int remainder = decimal % 2;//takes the remainder of the iteration
decimal = decimal / 2;//halves the decimal number
result = result + (remainder * base);//pseudo concatenation of the binary
base = base * 10;//increases the base multiplier to continue filling out the binary leftward
}
return result;//returns result after loop has finished
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();//scan the input to obtain the decimal number
int binaryForm = conversion(n);//convert the decimal to binary and assign to binaryForm variable
String stringForm = Integer.toString(binaryForm);//convert binaryForm to a String
int counter = 1;
int max = 1;
char testArray[] = stringForm.toCharArray();//send stringForm to fill out testArray
for(int i = 0; i < testArray.length - 1; i++){//loops through testArray to test stringForm values
if(testArray[i] == testArray[i + 1] && testArray[i] == '1'){//if consecutive values equal char 1, increase counter
counter += 1;
if(counter > max){
max = counter;//if counter is higher than current maxCounter, increase maxCounter
}
}
else {//if consecutive values do not equal 1, reset counter
counter = 1;
}
}
System.out.print(max);//print the maximum consecutive values for the decimal input when converted to binary
}
}
You are trying to create a binary representation of a decimal number using an integer. This will work for smaller numbers but it doesn't take long for you to reach an overflow. You should use a string representation of the binary number like so
String numBin = "";
while(num > 0)
{
numBin = num % 2 + numBin;
num = num / 2;
}
System.out.println("Binary Representation: " + numBin);
Then take that string and loop through it calculating the consecutive counts of 1's
int consecutiveCount = 0;
for(int i = 0; i < numBin.length() - 1; i++)
{
if(numBin.charAt(i) == '1' && numBin.charAt(i + 1) == '1')
{
consecutiveCount++;
}
}
System.out.println("Consecutive Count: " + consecutiveCount);
Output
Number: 261141
Binary Representation: 111111110000010101
Consecutive Count: 7
Number: 3
Binary Representation: 11
Consecutive Count: 1
Number: 18
Binary Representation: 10010
Consecutive Count: 0
Number: 1111111
Binary Representation: 100001111010001000111
Consecutive Count: 5
Write a static method called digitsInARow that takes an integer n as a parameter and that returns the highest number of digits that appear in a row in the base-10 representation of n. For many numbers the answer will be 1 because they don't have adjacent digits that match. But for a number like 3555585, the answer is 4 because there are four occurrences of the digit 5 that appear in a row. You are NOT allowed to use a String to solve this problem. You may assume that the value passed to the method is greater than or equal to 0.
public static int digitsInARow(int n) {
if (n / 10 == 0) {
return 1;
}
int count = 0;
int count1 = 0;
while (n > 0) {
int digit = n % 10;
int a = n / 10;
if (digit == a % 10) {
count++;
} else {
count1 = Math.max(count1, count);
count = 0;
}
n = n / 10;
}
return Math.max(count, count1);
}
I know the if statement is messed up. I am trying to figure out a way to compare consecutive digits WITHOUT using Integer class or String class. Any suggestions?
The problem with your code is that count keeps track of the current count, not of the highest count. You need to add a variable that tracks the highest count as well, and update it each time you process a digit, before resetting count back to zero.
Don't forget to update the highest count when you exit the loop, in case then-current count is greater than the previously found max.
public int sumOfDigits(int num){
return num == 0 ? 0 : num % 10 + sumOfDigits(num/10);
}
This is a recursive calculation of the sum of digits - as long as you haven't consumed all the digits, it adds the last one with the sum of all the previous ones.
sumOfDigits is a method which accepts int argument and the return type is also int.
If 0 is passed then it will return 0 other wise it will return num % 10 + sumOfDigits(num/10)
If a number other than 0 is passed this will continue as long as entered number becomes 0
return num == 0 ? 0 : num % 10 + sumOfDigits(num/10);
Is equivalent to:
if(num==0)
{
return 0;
}
else
{
return num % 10 + sumOfDigits(num/10); // this is recursive call. It gets called until num is reduce to 0
}
This basically calulates as following:
If num=768 result= 7+6+8.
That is the Java ternary operator. It is similar to ternary operators in other languages. In this case:
return <boolean expression> ? <if true> : <if false>;
You have posted a recursive algorithm to calculate the sum of digits in an integer.
Two equivalent methods are posted below:
public int sumOfDigitsIf(int num) {
if (num == 0) {
return 0;
} else {
return num % 10 + sumOfDigitsIf(num / 10);
}
}
public int sumOfDigitsLoop(int num) { // useful to examine if you aren't used to recursive algorithms
int value = 0;
while (num > 0) {
value += num % 10;
num /= 10;
}
return value;
}
This function calculates the sum of the digits of the number recursively. First, if the number is 0, it returns 0, as the sum of the digits of 0 is 0. Then, it calculates the digit in the 1s place with num % 10, and adds that to the sum of the digits of the remaining places, num / 10 is the remaining places, and it calls sumOfDigits() on that number.
This method calculates sum of the numbers representing base 10 integer numbers. The method is called recursively with % operator to separate digits in the number and then add them to form the result.
Eg - 234 into 2 + 3 + 4 = 9
However, if you pass a integer in base other than base 10, the method still gives the result for base 10
Eg sumOfDigits(0b1011010) -> answer is 9 for 90 in base 10
sumOfDigits(0x532) -> answer is 7 for 1330 in base 10
Following is the change for binary and octal values to get the sum of the representing numbers
return num == 0 ? 0 : num % 2 + sumOfDigits(num / 2);
return num == 0 ? 0 : num % 8 + sumOfDigits(num / 8);
That's a Java ternary operator, but in most cases it is not used since if-else statements are much more readable, which can also do the same function ternary operators can do. But if you would like to make shorter code lines, then this is preferred.
I am trying to find a way to reverse a number without
Converting it to a string to find the length
Reversing the string and parsing it back
Running a separate loop to compute the Length
i am currently doing it this way
public static int getReverse(int num){
int revnum =0;
for( int i = Integer.toString(num).length() - 1 ; num>0 ; i-- ){
revnum += num % 10 * Math.pow( 10 , i );
num /= 10;
}
return revnum;
}
But I would Like to implement the above 3 conditions.
I am looking for a way , possibly using the bit wise shift operators or some other kind of bitwise operation.
Is it possible ? If so how ?
PS : If 1234 is given as input it should return 4321. I will only be reversing Integers and Longs
How about:
int revnum = 0;
while (num != 0) {
revnum = revnum * 10 + (num % 10);
num /= 10;
}
return revnum;
The code expects a non-negative input.
This may or may not matter to you, but it's worth noting that getReverse(getReverse(x)) does not necessarily equal x as it won't preserve trailing zeroes.
How about this? It handles negative numbers as well.
public int getReverse(int num){
int rst=0;
int sign;
sign=num>0?1:-1;
num*=sign;
while(num>0){
int lastNum = num%10;
rst=rst*10+lastNum
num=num/10;
}
return rst*sign;
}
Integer.MAX_VALUE or Integer.MIN_VALUE is not at all considered in any of the solutions.
For eg: if the input is -2147483647 or 2147483647 the o/p will be 1126087180 and -1126087180 respectively.
Please try the below solutions where both the conditions are handled, so if at any point of time the number is going beyond the boundary conditions i.e., INPUT_VALUE > Integer.MAX_VALUE or INPUT_VALUE < Integer.MIN_VALUE it would return 0
class ReversingIntegerNumber {
public int reverse(int originalNum) {
boolean originalIsNegative = originalNum > 0 ? false : true;
int reverseNum = 0;
int modValue;
originalNum = Math.abs(originalNum);
while(originalNum != 0) {
modValue = originalNum % 10;
if(reverseNum > (Integer.MAX_VALUE - modValue)/10) {
return 0;
}
reverseNum = (reverseNum * 10) + modValue;
originalNum /= 10;
}
return originalIsNegative ? -1 * reverseNum : reverseNum;
}
}