Skip to content

Instantly share code, notes, and snippets.

@shiracamus
Created November 10, 2023 03:09
Show Gist options
  • Save shiracamus/d9e174a352c0048f2e39acfb74d8f1c6 to your computer and use it in GitHub Desktop.
Save shiracamus/d9e174a352c0048f2e39acfb74d8f1c6 to your computer and use it in GitHub Desktop.
四則演算を使わない加算処理(Qiitaに投稿された記事にコメントしたが記事は削除された)
import java.util.HashMap;
import java.util.Map;
class Digit { // 1桁数字
static final Map<Integer, Integer> next = new HashMap<>() {{
put(0, 1);
put(1, 2);
put(2, 3);
put(3, 4);
put(4, 5);
put(5, 6);
put(6, 7);
put(7, 8);
put(8, 9);
put(9, 0);
}};
protected int value = 0;
public void increment() {
value = next.get(value);
}
}
public class Digits extends Digit { // 複数桁数字
private Digit carry = null; // 上位桁
public Digits(int value) {
this.value = value;
}
@Override
public void increment() {
super.increment();
if (value == 0) {
if (carry == null) {
carry = new Digits(1);
} else {
carry.increment();
}
}
}
public void plus(int value) {
for (int i = 0; i < value; i++) {
increment();
}
}
@Override
public String toString() {
return String.format("%s%d", carry == null ? "" : carry, value);
}
public static void main(String[] args) {
Digits value = new Digits(6);
System.out.println(value);
value.plus(5);
System.out.println(value);
value.plus(12345678);
System.out.println(value);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment