7

LZ的贴子翻译如下：

n = -n;

LZ在四楼回复到：

int x = numberToInvertSign;
boolean pos = x > 0;
for(int i = 0; i < 2*Math.abs(x); i++){
if(pos){
numberToInvertSign--;
}
else{
numberToInvertSign++;
}
}

int n = ....;
n = (0xffffffff ^ n) + 1;

n = ~n + 1;

n = ~--n;

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);

public int invert(int i) {
return i - (i + i);
}
switch (i)
{
case 1: return -1;
case 2: return -2;
case 3: return -3;
// ... etc, you get the proper pattern
}

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;
}
}
}

还有用字符串的解决方案：
public int invert(int n) {
String nStr = String.valueOf(n);

if (nStr.startsWith("-")) {
nStr = nStr.replace("-", "");
} else {
nStr = "-" + nStr;
}

return Integer.parseInt(nStr);
}

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());
}
}

http://us.php.net/manual/en/function.abs.php#58508

<无标签>

crazyinsomnia

#### 引用来自“高庆丰”的帖子

你提了相同的问题？-12转换成12？

恶搞中国！河蟹社会！