Forum Stats

  • 3,728,221 Users
  • 2,245,576 Discussions
  • 7,853,386 Comments

Discussions

How do you Invert signed numbers?

843789
843789 Member Posts: 46,655 Green Ribbon
edited September 2009 in New To Java
Hi there.

A simple question: How can I invert the sign of an integer? ie) convert -12 to +12? No doubt there is a really simple way to do this, but I'm stumped, I cannot find anything and I've been working on this program all day.

I'll be very grateful to anyone who can let me know if Java provides a way to do this, or point me in the right direction if it takes some tweaking of binary numbers using the Math package or something.

Cheers!
«1

Comments

  • 843789
    843789 Member Posts: 46,655 Green Ribbon
  • 796262
    796262 Member Posts: 2,678
    edited August 2009
    Is this a joke? If not, try this:
    int x = numberToInvertSign;
    boolean pos = x > 0;
    for(int i = 0; i < 2*Math.abs(x); i++){
       if(pos){
          numberToInvertSign--;
       }
       else{
          numberToInvertSign++;
       }
    }
  • 843789
    843789 Member Posts: 46,655 Green Ribbon
    I knew it would be simple, but not that simple! I feel like a right dumbass now.

    Thanks very much paul.miner, you saved the day.
  • 843789
    843789 Member Posts: 46,655 Green Ribbon
    No joke, I just tried it and it worked.
  • 843789
    843789 Member Posts: 46,655 Green Ribbon
    paul.miner wrote:
    n = -n
    Not obscure enough! I prefer
     int n = ....;
     n = (0xffffffff ^ n) + 1;
  • 843789
    843789 Member Posts: 46,655 Green Ribbon
    sabre150 wrote:
    paul.miner wrote:
    n = -n
    Not obscure enough! I prefer
    int n = ....;
    n = (0xffffffff ^ n) + 1;
    Meh:
    n = ~n + 1;
  • 843789
    843789 Member Posts: 46,655 Green Ribbon
    Or better:
    n = ~--n;
  • 843789
    843789 Member Posts: 46,655 Green Ribbon
    paul.miner wrote:
    Meh:
    n = ~n + 1;
    :-)
  • JosAH
    JosAH Member Posts: 7,698
    sabre150 wrote:
    paul.miner wrote:
    n = -n
    Not obscure enough! I prefer
    int n = ....;
    n = (0xffffffff ^ n) + 1;
    Bah, that +1 operation is way too clear; better make that:
    n^= 0xffffffff;
    int m;
    for (m= 1; m != 0 && ((n&m) != 0); m<<= 1);
    n|= m;
    if (m == 0) n= m;
    else for (m >>= 1; m != 0; n^= m, m>>=1);
    kind regards,

    Jos ;-)
  • 843789
    843789 Member Posts: 46,655 Green Ribbon
    >
    else for (m >>= 1; m != 0; n^= m, m>>=1);
    Shouldn't this be an unsigned shift, at least for the initial shift?
    else for (m >>>= 1; m != 0; n^= m, m>>=1);
  • JosAH
    JosAH Member Posts: 7,698
    paul.miner wrote:
    Shouldn't this be an unsigned shift, at least for the initial shift?
    else for (m >>>= 1; m != 0; n^= m, m>>=1);
    Yep, you are correct; I now go spank myself thank you ;-)

    kind regards,

    Jos
  • paul.miner wrote:
    Shouldn't this be an unsigned shift, at least for the initial shift?
    else for (m >>>= 1; m != 0; n^= m, m>>=1);
    Thank goodness we now have the correct form to use in all our code.
  • 843789
    843789 Member Posts: 46,655 Green Ribbon
    jschell wrote:
    paul.miner wrote:
    Shouldn't this be an unsigned shift, at least for the initial shift?
    else for (m >>>= 1; m != 0; n^= m, m>>=1);
    Thank goodness we now have the correct form to use in all our code.
    Especially since it only affects negating Integer.MIN_VALUE, the odd man out :)
  • jeisen
    jeisen Member Posts: 283
    You guys are all trying way too hard. Clearly, you can do it just with regular addition and subtraction:
    public int invert(int i) {
      return i - (i + i);
    }
  • 796447
    796447 Member Posts: 10,442
    JEisen wrote:
    You guys are all trying way too hard. Clearly, you can do it just with regular addition and subtraction:
    public int invert(int i) {
    return i - (i + i);
    }
    Nah, I think it should be a simple switch statement:
    switch (i)
    {
      case 1: return -1;
      case 2: return -2;
      case 3: return -3;
      // ... etc, you get the proper pattern
    }
  • 843789
    843789 Member Posts: 46,655 Green Ribbon
    I'll take yours, and raise you a constant:
    return i - (i * 2)
  • 843789
    843789 Member Posts: 46,655 Green Ribbon
    [This thread is now on Reddit.|http://www.reddit.com/r/programming/comments/9egb6/programming_is_hard/]
  • 843789
    843789 Member Posts: 46,655 Green Ribbon
  • 843789
    843789 Member Posts: 46,655 Green Ribbon
    edited August 2009
    You're all making this way too complex. The best way to make an absolute value is obviously to overflow int.
    int absoluteValue(int num)
    {
     int max = 0;
     for(int i = 0; true; ++i)
     {
      max = i > max ? i : max;
      if(i == num)
      {
       if(i >= max)
        return i;
       return -i;
      }
     }
    }
  • 843789
    843789 Member Posts: 46,655 Green Ribbon
    practissum wrote:
    The best way to make an absolute value
    Good for you but this is not what the OP wanted!
  • 843789
    843789 Member Posts: 46,655 Green Ribbon
    Haven't you guys ever heard that you're supposed to use String manipulation to invert numbers? ;-)
    public int invert(int n) {
        String nStr = String.valueOf(n);
    
        if (nStr.startsWith("-")) {
            nStr = nStr.replace("-", "");
        } else {
            nStr = "-" + nStr;
        }
    
        return Integer.parseInt(nStr);
    }
  • 843789
    843789 Member Posts: 46,655 Green Ribbon
    Use a non-deterministic algorithm (always a good choice since you don't have to do any analysis!)

    public int invert(int n) {
    Random r = new Random();
    while (true) {
    int s = r.nextInt();
    if ((s + n) == 0) {
    return s;
    }
    }
    }
  • 843789
    843789 Member Posts: 46,655 Green Ribbon
    edited August 2009
    come on...
    -Math.abs(value)
    //that fails :D

    Edited by: Freakman86 on Aug 27, 2009 1:42 AM
  • 800308
    800308 Member Posts: 8,227
    paul.miner wrote:
    [This thread is now on Reddit.|http://www.reddit.com/r/programming/comments/9egb6/programming_is_hard/]
    LMA right O!
  • 3004
    3004 Member Posts: 204,171
    Guys, guys. For shame! You all seem to be forgetting that Java is an object oriented language. Leave the bit-twiddling for C and assembly. To do this the Java way we need polymorphism, factory methods, exceptions!

    This should be a decent start. I'll leave the unit tests as an exercise for the reader.
    public interface Negatable<T extends Number> {
      T value();
      T negate();
    }
    
    
    
    public abstract class NegatableInteger implements Negatable<Integer> {
      private final int value;
    
      protected NegatableInteger(int value) {
        this.value = value;
      }
    
      public static NegatableInteger createNegatableInteger(int value) {
        if (value > 0) {
          return new NegatablePositiveInteger(value);
        }
        else if (value == Integer.MIN_VALUE) {
          throw new IllegalArgumentException("cannot negate " + value);
        }
        else if (value < 0) {
          return new NegatableNegativeInteger(value);
        }
        else {
          return new NegatableZeroInteger(value);
        }
      }
    
      public Integer value() {
        return value;
      }
    
      public Integer negate() {
        String negatedString = negateValueAsString ();
        Integer negatedInteger = Integer.parseInt(negatedString);
        return negatedInteger;
      }
    
      protected abstract String negateValueAsString ();
    }
    
    
    
    public class NegatablePositiveInteger extends NegatableInteger {
      public NegatablePositiveInteger(int value) {
        super(value);
      }
    
      protected String negateValueAsString () {
        String valueAsString = String.valueOf (value());
        return "-" + valueAsString;
      }
    }
    
    
    
    public class NegatableNegativeInteger extends NegatableInteger {
      public NegatableNegativeInteger (int value) {
        super(value);
      }
    
      protected String negateValueAsString () {
        String valueAsString = String.valueOf (value());
        return valueAsString.substring(1);
      }
    }
    
    
    
    public class NegatableZeroInteger extends NegatableInteger {
      public NegatableZeroInteger (int value) {
        super(value);
      }
    
      protected String negateValueAsString () {
        return String.valueOf (value());
      }
    }
This discussion has been closed.