Output of converting binary to Decimal not expected? - java

Given a binary number as input convert it into base 10 (decimal system). Note that to convert a number 100111 from binary to decimal, the value is 1*2^5 + 0*2^4 + 0*2^3 + 1*2^2 + 1*2^1+ 1*2^0. Also note that 5 here is the length of the binary number.
MyApproach
To convert to decimal,I first converted the code from String to decimal.Then I solved the number till it is greater than 0 and solved the expression.
For example for number 10=0*2^0+1*2^1 and solved the expression in the code.
I am getting a wrong Ans on the last test case.
Can anyone guide me what is wrong in my code.?
Below is my code:
public int convert(String binary)
{
int p=0;
int decimal=0;
int number=Integer.parseInt(binary);
while(number>0)
{
int temp = number%10;
decimal += temp*Math.pow(2, p);
number = number/10;
p++;
//write your code here
}
return decimal;
}
}
Parameters ActualOutput ExpectedOutput
'10011010010' null 1234

Max value of integer is (2^31-1) and the value that you are parsing to int from string in greater than that. Hence try to use Long in place of int ..
below code is working fine.. please check it below..
public static int convert(String binary)
{
int p=0;
int decimal=0;
long number=Long.parseLong(binary);
while(number>0)
{
long temp = number%10;
decimal += temp*Math.pow(2, p);
number = number/10;
p++;
//write your code here
}
return decimal;
}

Simpler, without pow :
int s=binary.length();
for (int pos=0;pos<s;pos++)
{
char c=binary.charAt(pos);
if (c=='1') decimal+=1;
if (pos<s-1) decimal*=2;
}

Why convert it to decimal first? This is quite easy:
public static void main( String[] args ) {
String str = "10011010010";
int len = str.length();
long mult = 1;
long val = 0;
for (int i = len - 1; i >= 0; i--) {
if ( str.charAt( i ) == '1' ) {
val += mult;
}
mult *= 2;
}
System.out.println( val );
}

Your input is above the limit of int in Java, which is 2,147,483,647.
Even if if you change it to long, you won't be able to convert values above 1000000000000000000 (which is equal to 262144 in decimal). Best solution is to calculate by taking character by character without converting the whole string.
So, try the following code,
public static long convert(String binary) {
long pow = 1, decimal = 0;
for (int i = (binary.length() - 1); i >= 0; i--) {
if (binary.charAt(i) == '1') {
decimal += pow;
}
pow *= 2;
}
return decimal;
}

Related

Write a method that will convert the supplied binary digit (as a string) to a decimal number

The aim of this method is to convert the supplied binary digit (as a string) to a decimal number, but I am not getting the result the question wants with the code I have for example convertToDecimal("01101011") = 107, and I'm am unsure I believe im converting the binary to decimal number right.
for example:
Test
System.out.println(convertToDecimal("11001101")); = 205
ive tried a while loop and creating ints but it's just not giving me the same results
public static int binaryToDecimal(String binary) {
int decimal = 0;
int power = 0;
int currentIndex = binary.length() - 1;
while (currentIndex>=0) {
int currentDigit = binary.charAt(currentIndex) - '0';
decimal += currentDigit * Math.pow(2, power);
power++;
currentIndex--;
}
return decimal;
}
I expected to the output to be:
convertToDecimal("01101011") = 107
convertToDecimal("00001011") = 11 ,
System.out.println(convertToDecimal("11001101")); = 205
but none were right
I ran your code, and it worked. But I need to make one simple change:
System.out.println(convertToDecimal("11001101")); = 205
must be changed to:
System.out.println(binaryToDecimal("11001101")); = 205
because binaryToDecimal() is the actual name of your function:
public static int binaryToDecimal(String binary) {
int decimal = 0;
int power = 0;
int currentIndex = binary.length() - 1;
while (currentIndex>=0) {
int currentDigit = binary.charAt(currentIndex) - '0';
decimal += currentDigit * Math.pow(2, power);
power++;
currentIndex--;
}
return decimal;
}
After that, it all works fine.

Datatype for getting input for over 30 digits

I have a serious problem. I need to get a number say
123454466666666666666665454545454454544598989899545455454222222222222222
and give the total of that number. I was trying for a long time. I couldn't get the answer. The problem is I didn't know which data type to use. I have tried it long. It accepts only 18 digits. I have gone through BigInteger. But I couldn't make arithmetic operations with it. so help me out with this problem..
1.Get it as a string
2.get length of it.
3.Loop through each character of it.
4.check if the character is a number.
5.If yes parse it to int.
6.Add all numbers together in the loop
OR
Use BigDecimal
You can get the result from the below code.
String string = "123454466666666666666665454545454454544598989899545455454222222222222222";
int count = 0;
for (int i = 0; i < string.length(); i++) {
count += Integer.parseInt(String.valueOf(string.charAt(i)));
}
System.out.println(count);
Just use it as a String. That's the easiest way to go for the task at hand.
public class Test022 {
public static void main(String[] args) {
String s = "123454466666666666666665454545454454544598989899545455454222222222222222";
int sum = 0;
for (int i=0; i<s.length(); i++){
sum += s.charAt(i) - '0';
}
System.out.println(sum);
}
}
i can suggest using this code and the numbers as String
/**
* Adds two non-negative integers represented as string of digits.
*
* #exception NumberFormatException if either argument contains anything other
* than base-10 digits.
*/
public static String add(String addend1, String addend2) {
StringBuilder buf = new StringBuilder();
for ( int i1 = addend1.length() - 1, i2 = addend2.length() - 1, carry = 0;
(i1 >= 0 && i2 >= 0) || carry != 0;
i1--, i2-- ) {
int digit1 = i1 < 0 ? 0 :
Integer.parseInt(Character.toString(addend1.charAt(i1)));
int digit2 = i2 < 0 ? 0 :
Integer.parseInt(Character.toString(addend2.charAt(i2)));
int digit = digit1 + digit2 + carry;
if (digit > 9) {
carry = 1;
digit -= 10;
} else {
carry = 0;
}
buf.append(digit);
}
return buf.reverse().toString();
}
BigInteger does support methods like add/multiply etc. See this for details.
BigInteger operand1 = new BigInteger("123454466666666666666665454545454454544598989899545455454222222222222222");
BigInteger operand2 = new BigInteger("123454466666666666666665454545454454544598989899545455454222222222222222");
System.out.println(operand1.add(operand2));
System.out.println(operand1.subtract(operand2));
System.out.println(operand1.multiply(operand2));
System.out.println(operand1.divide(operand2));

string - double in java without using parse

I need to create a program that converts a string to double.
public class Convert{
public static void main(String args[]){
String num="124023211.123";
int d=0,g=0,c=0,fnl=0,h=0,v=0;
double fnl2=0;
int exp=(num.indexOf(".")-1);
while(num.charAt(d)!='.'){
g=num.charAt(d)-48;
int k = 1;
for(int f=0;f<exp;f++){
k=(k*10);
}
fnl+=(k*g);
d++;
exp--;
}
num=(num.substring(d+1) );
//System.out.println(fnl);
//System.out.println(num);
while(h!=num.length()){
v=num.charAt(h)-48;
double j=1;
int exp1=num.length();
for(int f1=0;f1<exp1;f1++){
j*=.10;
}
fnl2+=(h*j);
j++;
h++;
}
System.out.println(fnl2);
}
}
The first while loop converts the int part of the string and it works right. But the second while loop should result to the decimal portion of the string. I am having a hard time because double results to huge decimal numbers and it ruins the conversion, and also the second while loop prints the wrong answer.
int exp1=num.length();
This line is part of your problem. Your loop will always loops num.length() times, but num isn't changing in length (so always 3, in your case). This is causing all three numbers to be treated as thousandths.
Also, remember that decimal values can't be represented exactly in the IEEE-754 format. By doing all these multiplications and additions, you're introducing error into your result. Double.Parse is going to give you the best approximation possible for your number.
You can do the following
String s="124023211.123";
int i;
double result = 0.0f, result2 = 0.0f;
for (i = 0; i < s.length(); i++)
if (s.charAt(i) == '.')
break;
else
result = result * 10 + (s.charAt(i) - '0');
for (i = s.length()-1 ; i>=0 ; i--)
if (s.charAt(i) == '.')
break;
else
result2 = result2 / 10 + (s.charAt(i) - '0');
if (i>=0)
result += result2/10;
Tested for: 11, 3.0, 6.00000, 0005.000, .12, and 124023211.123
Of course, you will not get always the exact value, because sometimes it will be written as an expression as double, like the number you provided. And there are some numbers that have no representation in the binary system.
Try this one it is working fine tested for valid data
public class Sample1 {
public static void main(String args[]){
String num="122312312.2331231";
String s1 = num.substring(0,num.indexOf("."));
String s2 = num.substring(num.indexOf(".") + 1,num.length());
System.out.println(s1);
System.out.println(s2);
double n1 = 0;
double n2 = 0;
for(int i=0;i<s1.length();i++){
double d = s1.charAt(i) - '0';
n1 = n1*10;
n1 += d;
}
System.out.println(n1);
for(int i=0;i<s2.length();i++){
double d = s2.charAt(i) - '0';
//n2 = n2/;
n2 += d/number(i+1);
}
System.out.println(n1+n2);
}
public static long number(int n2){
long d = 10l;
if(n2>1)
d = 10 * number(n2-1);
return d;
}
}
Gautam Sonar

Iterate through each digit in a number

I am trying to create a program that will tell if a number given to it is a "Happy Number" or not. Finding a happy number requires each digit in the number to be squared, and the result of each digit's square to be added together.
In Python, you could use something like this:
SQUARE[d] for d in str(n)
But I can't find how to iterate through each digit in a number in Java. As you can tell, I am new to it, and can't find an answer in the Java docs.
You can use a modulo 10 operation to get the rightmost number and then divide the number by 10 to get the next number.
long addSquaresOfDigits(int number) {
long result = 0;
int tmp = 0;
while(number > 0) {
tmp = number % 10;
result += tmp * tmp;
number /= 10;
}
return result;
}
You could also put it in a string and turn that into a char array and iterate through it doing something like Math.pow(charArray[i] - '0', 2.0);
Assuming the number is an integer to begin with:
int num = 56;
String strNum = "" + num;
int strLength = strNum.length();
int sum = 0;
for (int i = 0; i < strLength; ++i) {
int digit = Integer.parseInt(strNum.charAt(i));
sum += (digit * digit);
}
I wondered which method would be quickest to split up a positive number into its digits in Java, String vs modulo
public static ArrayList<Integer> splitViaString(long number) {
ArrayList<Integer> result = new ArrayList<>();
String s = Long.toString(number);
for (int i = 0; i < s.length(); i++) {
result.add(s.charAt(i) - '0');
}
return result; // MSD at start of list
}
vs
public static ArrayList<Integer> splitViaModulo(long number) {
ArrayList<Integer> result = new ArrayList<>();
while (number > 0) {
int digit = (int) (number % 10);
result.add(digit);
number /= 10;
}
return result; // LSD at start of list
}
Testing each method by passing Long.MAX_VALUE 10,000,000 times, the string version took 2.090 seconds and the modulo version 2.334 seconds. (Oracle Java 8 on 64bit Ubuntu running in Eclipse Neon)
So not a lot in it really, but I was a bit surprised that String was faster
In the above example we can use:
int digit = Character.getNumericValue(strNum.charAt(i));
instead of
int digit = Integer.parseInt(strNum.charAt(i));
You can turn the integer into a string and iterate through each char in the string. As you do that turn that char into an integer
This code returns the first number (after 1) that fits your description.
public static void main(String[] args) {
int i=2;
// starting the search at 2, since 1 is also a happy number
while(true) {
int sum=0;
for(char ch:(i+"").toCharArray()) { // casting to string and looping through the characters.
int j=Character.getNumericValue(ch);
// getting the numeric value of the current char.
sum+=Math.pow(j, j);
// adding the current digit raised to the power of itself to the sum.
}
if(sum==i) {
// if the sum is equal to the initial number
// we have found a number that fits and exit.
System.out.println("found: "+i);
break;
}
// otherwise we keep on searching
i++;
}
}

Counting trailing zeros of numbers resulted from factorial

I'm trying to count trailing zeros of numbers that are resulted from factorials (meaning that the numbers get quite large). Following code takes a number, compute the factorial of the number, and count the trailing zeros. However, when the number is about as large as 25!, numZeros don't work.
public static void main(String[] args) {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
double fact;
int answer;
try {
int number = Integer.parseInt(br.readLine());
fact = factorial(number);
answer = numZeros(fact);
}
catch (NumberFormatException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static double factorial (int num) {
double total = 1;
for (int i = 1; i <= num; i++) {
total *= i;
}
return total;
}
public static int numZeros (double num) {
int count = 0;
int last = 0;
while (last == 0) {
last = (int) (num % 10);
num = num / 10;
count++;
}
return count-1;
}
I am not worrying about the efficiency of this code, and I know that there are multiple ways to make the efficiency of this code BETTER. What I'm trying to figure out is why the counting trailing zeros of numbers that are greater than 25! is not working.
Any ideas?
Your task is not to compute the factorial but the number of zeroes. A good solution uses the formula from http://en.wikipedia.org/wiki/Trailing_zeros (which you can try to prove)
def zeroes(n):
i = 1
result = 0
while n >= i:
i *= 5
result += n/i # (taking floor, just like Python or Java does)
return result
Hope you can translate this to Java. This simply computes [n / 5] + [n / 25] + [n / 125] + [n / 625] + ... and stops when the divisor gets larger than n.
DON'T use BigIntegers. This is a bozosort. Such solutions require seconds of time for large numbers.
You only really need to know how many 2s and 5s there are in the product. If you're counting trailing zeroes, then you're actually counting "How many times does ten divide this number?". if you represent n! as q*(2^a)*(5^b) where q is not divisible by 2 or 5. Then just taking the minimum of a and b in the second expression will give you how many times 10 divides the number. Actually doing the multiplication is overkill.
Edit: Counting the twos is also overkill, so you only really need the fives.
And for some python, I think this should work:
def countFives(n):
fives = 0
m = 5
while m <= n:
fives = fives + (n/m)
m = m*5
return fives
The double type has limited precision, so if the numbers you are working with get too big the double will be only an approximation. To work around this you can use something like BigInteger to make it work for arbitrarily large integers.
You can use a DecimalFormat to format big numbers. If you format your number this way you get the number in scientific notation then every number will be like 1.4567E7 this will make your work much easier. Because the number after the E - the number of characters behind the . are the number of trailing zeros I think.
I don't know if this is the exact pattern needed. You can see how to form the patterns here
DecimalFormat formater = new DecimalFormat("0.###E0");
My 2 cents: avoid to work with double since they are error-prone. A better datatype in this case is BigInteger, and here there is a small method that will help you:
public class CountTrailingZeroes {
public int countTrailingZeroes(double number) {
return countTrailingZeroes(String.format("%.0f", number));
}
public int countTrailingZeroes(String number) {
int c = 0;
int i = number.length() - 1;
while (number.charAt(i) == '0') {
i--;
c++;
}
return c;
}
#Test
public void $128() {
assertEquals(0, countTrailingZeroes("128"));
}
#Test
public void $120() {
assertEquals(1, countTrailingZeroes("120"));
}
#Test
public void $1200() {
assertEquals(2, countTrailingZeroes("1200"));
}
#Test
public void $12000() {
assertEquals(3, countTrailingZeroes("12000"));
}
#Test
public void $120000() {
assertEquals(4, countTrailingZeroes("120000"));
}
#Test
public void $102350000() {
assertEquals(4, countTrailingZeroes("102350000"));
}
#Test
public void $1023500000() {
assertEquals(5, countTrailingZeroes(1023500000.0));
}
}
This is how I made it, but with bigger > 25 factorial the long capacity is not enough and should be used the class Biginteger, with witch I am not familiar yet:)
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in = new Scanner(System.in);
System.out.print("Please enter a number : ");
long number = in.nextLong();
long numFactorial = 1;
for(long i = 1; i <= number; i++) {
numFactorial *= i;
}
long result = 0;
int divider = 5;
for( divider =5; (numFactorial % divider) == 0; divider*=5) {
result += 1;
}
System.out.println("Factorial of n is: " + numFactorial);
System.out.println("The number contains " + result + " zeroes at its end.");
in.close();
}
}
The best with logarithmic time complexity is the following:
public int trailingZeroes(int n) {
if (n < 0)
return -1;
int count = 0;
for (long i = 5; n / i >= 1; i *= 5) {
count += n / i;
}
return count;
}
shamelessly copied from http://www.programcreek.com/2014/04/leetcode-factorial-trailing-zeroes-java/
I had the same issue to solve in Javascript, and I solved it like:
var number = 1000010000;
var str = (number + '').split(''); //convert to string
var i = str.length - 1; // start from the right side of the array
var count = 0; //var where to leave result
for (;i>0 && str[i] === '0';i--){
count++;
}
console.log(count) // console shows 4
This solution gives you the number of trailing zeros.
var number = 1000010000;
var str = (number + '').split(''); //convert to string
var i = str.length - 1; // start from the right side of the array
var count = 0; //var where to leave result
for (;i>0 && str[i] === '0';i--){
count++;
}
console.log(count)
Java's doubles max out at a bit over 9 * 10 ^ 18 where as 25! is 1.5 * 10 ^ 25. If you want to be able to have factorials that high you might want to use BigInteger (similar to BigDecimal but doesn't do decimals).
I wrote this up real quick, I think it solves your problem accurately. I used the BigInteger class to avoid that cast from double to integer, which could be causing you problems. I tested it on several large numbers over 25, such as 101, which accurately returned 24 zeros.
The idea behind the method is that if you take 25! then the first calculation is 25 * 24 = 600, so you can knock two zeros off immediately and then do 6 * 23 = 138. So it calculates the factorial removing zeros as it goes.
public static int count(int number) {
final BigInteger zero = new BigInteger("0");
final BigInteger ten = new BigInteger("10");
int zeroCount = 0;
BigInteger mult = new BigInteger("1");
while (number > 0) {
mult = mult.multiply(new BigInteger(Integer.toString(number)));
while (mult.mod(ten).compareTo(zero) == 0){
mult = mult.divide(ten);
zeroCount += 1;
}
number -= 1;
}
return zeroCount;
}
Since you said you don't care about run time at all (not that my first was particularly efficient, just slightly more so) this one just does the factorial and then counts the zeros, so it's cenceptually simpler:
public static BigInteger factorial(int number) {
BigInteger ans = new BigInteger("1");
while (number > 0) {
ans = ans.multiply(new BigInteger(Integer.toString(number)));
number -= 1;
}
return ans;
}
public static int countZeros(int number) {
final BigInteger zero = new BigInteger("0");
final BigInteger ten = new BigInteger("10");
BigInteger fact = factorial(number);
int zeroCount = 0;
while (fact.mod(ten).compareTo(zero) == 0){
fact = fact.divide(ten);
zeroCount += 1;
}
}

Categories