1

so I'm trying to take an int array and reverse every element that has more than three digits. i.e. change 147 -> 741

I'm new to java and do not even know where to start with this.

Here is the array I am trying to do this with.

int codedMessage[] = {334, 384, 105, 222, 61, 2, 175, 228, 114, 235, 241, 
                      213, 206, 3, 321, 152, 214, 137, 224};

Any help is greatly appreciated! Every time I try and look for help I just find stuff on reversing the order of an array because I don't really know how to google my question correctly i guess.

NoobCoderChick
  • 617
  • 3
  • 21
  • 40
  • 1
    Look into converting each int > 99 into a string, treating it as a character array to reverse, and converting it back to the reversed int. – J0e3gan Sep 07 '15 at 05:11

8 Answers8

3

You can walk through the array codedMessage and check if the value has 3 or more digits (i.e. is greater than 99). If so, then convert to a String, reverse it, and then write it back to the array in place.

int codedMessage[] = {334, 384, 105, 222, 61, 2, 175, 228, 114, 235, 241, 
                      213, 206, 3, 321, 152, 214, 137, 224};

for (int i=0; i < codedMessage.length; ++i) {
    if (codedMessage[i] > 99) {
        String value = String.valueOf(codedMessage[i]);
        String valueReversed = new StringBuilder(value).reverse().toString();
        codedMessage[i] = Integer.parseInt(valueReversed);
    }
}

System.out.print("{");
for (int i=0; i < codedMessage.length; ++i) {
    if (i > 0) { System.out.print(", "); }
    System.out.print(codedMessage[i]);
}
System.out.print("}");

Output:

{433, 483, 501, 222, 61, 2, 571, 822, 411, 532, 142, 312, 602, 3, 123, 251, 412, 731, 422}
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
  • @Andreas Autoboxing will take of this. In any case, taking your advice will only move around the boxing operation; it won't eliminate it. – Tim Biegeleisen Sep 07 '15 at 05:17
  • You got my up-vote for being first to suggest `StringBuilder.reverse()`. ;-) – Andreas Sep 07 '15 at 05:20
  • So is this a better option to convert to a string and use StringBuilder rather than using math operation and keeping it an integer first – NoobCoderChick Sep 07 '15 at 05:35
  • @user3862586 I would opt for just reversing the digits as a String. You're not doing a math operation here, quite the contrary, you are shifting around the characters of each number. – Tim Biegeleisen Sep 07 '15 at 05:37
2

Try this (codedMessage[i] which is printed at the end will contain the reversed number. I used main() but you could call a function):

public static void main(String[] args) {
    int[] codedMessage = {123,456, 789};
    int temp = 0;
    for(int i=0; i<codedMessage.length;i++){
        temp = 0;
        if(codedMessage[i]/100>=1){
            while(codedMessage[i]>0){
                temp = temp*10 + codedMessage[i] %10;
                codedMessage[i] = codedMessage[i]/10;                   
            }
            codedMessage[i] = temp;
            System.out.println(codedMessage[i]);
        }
    }

}
2

The other methods use strings, which are pretty slow compared to just doing integer operations:

public int reverseNumber(int number){

    int reverse = 0;
    while(number != 0){
        reverse = (reverse*10)+(number%10);
        number = number/10;
    }
    return reverse;
}

And then just iterate over the array

for(int code : codedMessage){
    System.out.print(reverseNumber(code))
}

How to only reverse numbers that are bigger than 99 is left as an exercise to the user.

Source for reversing a number

Czarek
  • 597
  • 1
  • 10
  • 20
  • You should check for a three digit number though – Sweeper Sep 07 '15 at 05:25
  • Yeah checking for a three digit number was the easy part lol, just wasn't sure where to go from there. Wow thank everyone! I can't believe you all got back to me so quickly!! – NoobCoderChick Sep 07 '15 at 05:32
  • @TimBiegeleisen 20ms seems like quite a bit of an improvement to be honest. Does it matter when iterating over 100k numbers? **No.** Does it matter if you frequently iterate over millions of numbers? **Yes.** – Czarek Sep 07 '15 at 05:53
1

First you need to break the problem into smaller steps. Try working backwards and see if you can figure out how to do each of these encapsulated steps.

  1. Reverse the digits of an element.
  2. Check if an element has three or more digits.
  3. Traverse through the array and examine each element.

Good luck!

Hayley Guillou
  • 3,953
  • 4
  • 24
  • 34
  • #1 was what I was having problems with. – NoobCoderChick Sep 07 '15 at 05:55
  • @user3862586 breaking your problem into smaller steps often helps for searching for solutions. You mentioned that you kept getting results for reversing an array, when you should have been searching how to reverse an int. – Hayley Guillou Sep 07 '15 at 06:11
0

I will just give you some general help because that is best way to learn in my opinion.

First, loop through all the elements in the array like this:

for (int number : codedMessage) {
    if (number > 99)
        continue;
    //Here you want to handle three digit numbers.
}

Now let's how you can reverse a number. I suggest that you convert a number to a string using Integer.toString and reverse that string and convert it back to a number using Integer.parseInt. I will show you how to reverse a string.

StringBuilder builder = new StringBuilder(str) //str is the string you want to reverse
builder.reverse();
String revresed = builder.toString();

Now reversed is the reversed string as you can tell by its name. So now it's your turn to combine the above and create your wonderful program!

Sweeper
  • 213,210
  • 22
  • 193
  • 313
0

it could be like this:

for(int i = 0; i < codedMessage.length ; i++)
   if (codedMessage[i]>99)
        codedMessage[i] = Integer.parseInt(new StringBuilder(new String (codedMessage[i]+"")).reverse().toString());
Kh.Taheri
  • 946
  • 1
  • 10
  • 25
0

In the below code I have created a reverse function which reverse the number if its length is 3 or more and returns the integer value.

    package com;
    public class Reverse {
    public static void main(String args[])
    {
        int codedMessage[] = {334, 384, 105, 222, 61, 2, 175, 228, 114, 235, 241, 
                  213, 206, 3, 321, 152, 214, 137, 224};
        String num;
    int message[]=new int[codedMessage.length];
    for(int i=0; i<codedMessage.length; i++)
    {           
        num=codedMessage[i]+"";
        if(num.length()>=3)
        {
            message[i]=reverse(num);
            System.out.println("Reverse="+message[i]);
        }
        else
        {
            message[i]=codedMessage[i];
            System.out.println(message[i]);
        }        
    }
}
    public static int reverse(String num) 
    {
        int number;
        number=Integer.parseInt(""+(new StringBuffer(num).reverse()));        
        return number;
    }
}
Piyush Yawalkar
  • 252
  • 1
  • 4
  • 17
0

As covered by most of the other answers, the easiest is to use StringBuilder.reverse(). The following is optimized to minimize the allocations to 1 StringBuilder (global), plus 1 String per reversed number.

int codedMessage[] = {334, 384, 105, 222, 61, 2, 175, 228, 114, 235, 241, 
                      213, 206, 3, 321, 152, 214, 137, 224, 123456789};

// Reverse digits of all numbers with 3 or more digits
StringBuilder buf = new StringBuilder();
for (int i = 0; i < codedMessage.length; i++)
    if (codedMessage[i] > 99) {
        buf.setLength(0);
        codedMessage[i] = Integer.parseInt(buf.append(codedMessage[i]).reverse().toString());
    }

// Print result
System.out.println(Arrays.toString(codedMessage));

Added the number 123456789 to show reversal of more than 3 digits:

[433, 483, 501, 222, 61, 2, 571, 822, 411, 532, 142, 312, 602, 3, 123, 251, 412, 731, 422, 987654321]
Andreas
  • 154,647
  • 11
  • 152
  • 247