-1
package code;

public class convert {

public int getPower(int power, int base){
    int ans = 1;
    for(int i=0; i<power; i++){
        ans = ans * base;

    }
    return ans;
}

public int baseten (String s, int base){
    int ret = 0;
    for(int i = 0; i<s.length(); i++){
        char cur = s.charAt(i);

        if(base >= 0 && base <= 9){
            int p = getPower(i, base);
            int v = p * (cur - '0');
            ret += v;   

        }

    }

    return ret;


    }
}

This is supposed to take a string and an int and return the base 10 value for that number. For example ("1001", 2) should return 9. It's currently giving me the wrong answer for several different tests and I'm not sure why. Thanks a lot!

assylias
  • 321,522
  • 82
  • 660
  • 783
inSo23
  • 39
  • 2
  • 8

2 Answers2

0

You're calculating your powers in the wrong order, giving the highest weight to the last digit rather than the first.

In fact, you don't need to calculate the power for each digit; instead you can multiply your accumulator directly:

for(int i = 0; i<s.length(); i++){
    char cur = s.charAt(i);
    if(base >= 0 && base <= 9){
        ret = ret * base + (cur - '0');
    }
}

Doing it this way works just the same as when you write a number on paper. If you write "10", and then you write another digit after that then the value becomes ten times greater (or two times, or whatever your base is). You add another digit and it gets ten (or two, or whatever) times greater again.

The only reason we have to think about tens and hundreds and thousands columns directly is when we read a decimal number aloud and we have to use the right words.

sh1
  • 4,324
  • 17
  • 30
-1

You getting wrong result just because of your binary conversion is not correct. Because when your string character s[0] the base power should be s.length()-1-i;

For Example: 0101 as input if i = 0 then 0*2^3+ if i = 1 then 1*2^2+ if i = 2 0*2^1+ if i = 3 1*2^0 it produce the result: 5

But in your code it will produce 10.

Here you have to declare a new variable called j int ret = 0,j = s.length()-1; and initialize it to the string length()-1 after that you have to pass the variable to the getPower() function like this: int p = getPower(j, base);

package code;

public class convert {

public int getPower(int power, int base){
    int ans = 1;
    for(int i=0; i<power; i++){
        ans = ans * base;

    }
    return ans;
}

public int baseten (String s, int base){
    int ret = 0,j = s.length()-1;
    for(int i = 0; i<s.length(); i++,j--){
        char cur = s.charAt(i);

        if(base >= 0 && base <= 9){
            int p = getPower(j, base);
            int v = p * (cur - '0');
            ret += v;   
        }
    }
    return ret;
    }
}

You can also do it in just one line:

int decimalVal = Integer.parseInt("0010101010",2);

It will produce the decimal value of the binary string.

Prosen Ghosh
  • 635
  • 7
  • 16