0

I have this psuedocode, which converts a binary value to a decimal value:

int powTwo = 1;
int dec = 0;
for each character in the string, starting with the last,
if (char == '1')
    dec += powTwo;
    powTwo *= 2;

How do i write the for each loop specified here, which looks at each character in the string, starting with the last? So far I have

for(Character c : someString)
c0der
  • 73
  • 1
  • 3
  • 11
  • Take a look at String.getBytes(). Or you could use a Vector to make it easier to iterate over the list of chars in reverse order. –  Jan 27 '15 at 17:01
  • you can use for loop instead to make it much simpler. do you require it only with for-each loop? it's doable but not as simple as regular for loop. – svjn Jan 27 '15 at 17:02
  • @jdv: That would look at it one *byte* at a time, not one *character* at a time. `charAt` would be more appropriate. – Jon Skeet Jan 27 '15 at 17:02
  • Long.parseLong(String s, int radix) or similar might simplify the job. – laune Jan 27 '15 at 17:05
  • @Jon%20Skeet, right you are. Why would we ever need anything other than US-ASCII? –  Jan 27 '15 at 17:05
  • 1
    @jdv: What makes you think that `char` is US-ASCII? I'm really not sure what you're trying to say. But converting the string to a byte array is unnecessary anyway... – Jon Skeet Jan 27 '15 at 17:08
  • @Jon: http://www.computerworld.com/article/2534312/operating-systems/the--640k--quote-won-t-go-away----but-did-gates-really-say-it-.html –  Jan 27 '15 at 17:14
  • Why not keep it simple and do it from left to right? – laune Jan 27 '15 at 17:15
  • @jdv: I fail to see how that's relevant. Basically, it's unclear whether you now genuinely think that `getBytes()` is a good idea, or whether you've changed your mind. (And why recommend `Vector` when `ArrayList` is more idiomatic?) – Jon Skeet Jan 27 '15 at 17:17
  • 1
    StringBuilder I think would be a better option than Vector myself. Just call its `reverse()` method and iterate with nothing complicated. – Drew Kennedy Jan 27 '15 at 17:19
  • @Jon: I acknowledged your char/byte point and made a small joke related to how common this particular conflation can be. Nothing sinister. (Because, without checking the API docs, I knew that Vector had handy methods for picking stuff off the end. I couldn't quite remember if StringBuilder or ArrayList had the same methods I was thinking of.) –  Jan 27 '15 at 17:23

3 Answers3

2

As said by Cory ,You can iterate from the last and compare each character.

An alternative approach is like this which literally has a for each loop as mentioned in your question

String reversedString=new StringBuffer(inputString).reverse().toString();
for(char c:reversedString.toCharArray()){
    // Do Whatever You want to Do here 
}

For-each loop (Advanced or Enhanced For loop):

The for-each loop introduced in Java5. It is mainly used to traverse array or collection elements. The advantage of for-each loop is that it eliminates the possibility of bugs and makes the code more readable.

Syntax of for-each loop:

for(data_type variable : array | collection){}  
Neeraj Jain
  • 7,643
  • 6
  • 34
  • 62
  • Even though you pretty much gave the same answer as me, I am giving you a +1 because of your explanation :-) – Ascalonian Jan 27 '15 at 17:33
  • Thanks @Ascalonian , I haven't read your post before answering , otherwise there is no need for me to write ,As your answer more than enough . and Yes thanks for +1 .. :) – Neeraj Jain Jan 27 '15 at 17:37
1

I'm going to assume this is homework and you're supposed to stay true to the pseudo-code and not use other shortcut methods available.

Pretty much the only thing the pseudo-code is missing is the for-loop. In your real code, instead of using for-in, I would just walk the string backwards:

int powTwo = 1;
int dec = 0;
// using the length of the string, start with a counter that is the length
// minus 1, decrement it by 1 until we get to 0
for (int i = someString.length() - 1; i >= 0; i--) {
    // Get the character at position i in the string
    char currentChar = someString.charAt(i);
    // Check for a "1"
    if (currentChar == '1') {
        dec += powTwo;
    }
    powTwo *= 2;
}
Cᴏʀʏ
  • 105,112
  • 20
  • 162
  • 194
1

I would recommend using StringBuilder#reverse. You can reverse the String and just loop over each character without any confusing for-loop

String initialValue = "Hello World!";
StringBuilder sb = new StringBuilder(initialValue);

String reversed = sb.reverse().toString();

char[] chars = reversed.toCharArray();

for (char c : chars) {
    // Check for a "1"
    if (c == '1') {
        dec += powTwo;
    }

    powTwo *= 2;
}

// output: !dlroW olleH
Ascalonian
  • 14,409
  • 18
  • 71
  • 103