-
Notifications
You must be signed in to change notification settings - Fork 23
Даниил Павлов, Беззнаковое большое целое число #3
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
DaniilPavlov
wants to merge
5
commits into
h31:master
Choose a base branch
from
DaniilPavlov:master
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,183 @@ | ||
| package ru.spbstu.kspt.task1; | ||
|
|
||
| /** | ||
| * Объекты данного класса (bbInt) - положительные числа длинной от одного, до 2^31-1 элементов | ||
| * Объекты умеют: | ||
| * +сравниваться | ||
| * +складываться | ||
| * +вычитаться | ||
| * +умножаться | ||
| * +делиться | ||
| * +находить остаток от деления | ||
| */ | ||
|
|
||
|
|
||
| class BigBigInt { | ||
|
|
||
| private String value;//Хранимое значение исходного огромного числа (bbInt) | ||
|
|
||
| String getValue() {//Получение значения bbInt | ||
|
Owner
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
|
||
| return value; | ||
| } | ||
|
|
||
| BigBigInt(String clearLine) { //Конструктор класса | ||
| //Преобразование строик в число без впередиидущих '0' и ' ' | ||
| clearLine = clearLine.replaceAll("\\D", ""); | ||
| clearLine = clearLine.replaceFirst("^0+(?!$)", ""); | ||
| //Обработка ввода строки не содержащей чисел | ||
| value = clearLine; | ||
| if (value.isEmpty()) { | ||
| System.out.println("Ошибка ввода числа"); | ||
| value = null; | ||
| } | ||
| } | ||
|
|
||
| static int compare(BigBigInt bbInt1, BigBigInt bbInt2) {//Сравнение двух bbInt | ||
| int result = -2; | ||
| if (bbInt1.value.compareTo(bbInt2.value) == 0) return 0; | ||
| if (bbInt1.value.length() > bbInt2.value.length()) return 1; | ||
| if (bbInt1.value.length() < bbInt2.value.length()) return -1; | ||
| for (int i = 0; i < Math.min(bbInt1.value.length(), bbInt2.value.length()); i++) { | ||
| if (bbInt1.value.charAt(i) > bbInt2.value.charAt(i)) return 1; | ||
| if (bbInt1.value.charAt(i) < bbInt2.value.charAt(i)) return -1; | ||
| } | ||
| System.out.println("Ошибка при попытке сравнения"); | ||
| return result; | ||
| } | ||
|
|
||
| static BigBigInt add(BigBigInt bbInt1, BigBigInt bbInt2) {//Сумма двух bbInt | ||
| StringBuilder builder = new StringBuilder(); | ||
| if (compare(bbInt1, bbInt2) < 0) { | ||
| BigBigInt bbInt = bbInt1; | ||
| bbInt1 = bbInt2; | ||
| bbInt2 = bbInt; | ||
| } | ||
| String answer = ""; | ||
| for (int i = 0; i < bbInt1.value.length() - bbInt2.value.length(); i++) { | ||
| builder.append("0"); | ||
| } | ||
| String str2 = builder.toString(); | ||
| str2 = str2 + bbInt2.value; | ||
| boolean ten = false; | ||
| int help; | ||
| for (int i = bbInt1.value.length() - 1; i >= 0; i--) { | ||
| if (ten) | ||
| help = 1; | ||
| else | ||
| help = 0; | ||
| help += Integer.parseInt(bbInt1.value.charAt(i) + "") + Integer.parseInt(str2.charAt(i) + ""); | ||
| if (help >= 10) { | ||
| ten = true; | ||
| help -= 10; | ||
| } else | ||
| ten = false; | ||
| builder = new StringBuilder(); | ||
| answer = builder.append(Integer.toString(help)).append(answer).toString(); | ||
| } | ||
| if (ten) | ||
| answer = "1" + answer; | ||
| return new BigBigInt(answer); | ||
| } | ||
|
|
||
| static BigBigInt subtract(BigBigInt bbInt1, BigBigInt bbInt2) {//Разность двух bbInt | ||
| StringBuilder builder = new StringBuilder(); | ||
| if (compare(bbInt1, bbInt2) < 0) { | ||
| BigBigInt bbInt = bbInt1; | ||
| bbInt1 = bbInt2; | ||
| bbInt2 = bbInt; | ||
| } | ||
| String answer = ""; | ||
| for (int i = 0; i < bbInt1.value.length() - bbInt2.value.length(); i++) { | ||
| builder.append("0"); | ||
| } | ||
| String str2 = builder.toString(); | ||
| str2 = str2 + bbInt2.value; | ||
| boolean ten = false; | ||
| int help; | ||
| for (int i = bbInt1.value.length() - 1; i >= 0; i--) { | ||
| if (ten) | ||
| help = -1; | ||
| else | ||
| help = 0; | ||
| help += Integer.parseInt(bbInt1.value.charAt(i) + "") - Integer.parseInt(str2.charAt(i) + ""); | ||
| if (help < 0) { | ||
| ten = true; | ||
| help += 10; | ||
| } else | ||
| ten = false; | ||
| builder = new StringBuilder(); | ||
| answer = builder.append(Integer.toString(help)).append(answer).toString(); | ||
| } | ||
| return new BigBigInt(answer); | ||
| } | ||
|
|
||
| static BigBigInt multiply(BigBigInt bbInt1, BigBigInt bbInt2) {//Произведение двух bbIn | ||
| if ((bbInt1 == new BigBigInt("0")) || (bbInt2 == new BigBigInt("0"))) return new BigBigInt("0"); | ||
| if (compare(bbInt1, bbInt2) < 0) { | ||
| BigBigInt bbInt; | ||
| bbInt = bbInt1; | ||
| bbInt1 = bbInt2; | ||
| bbInt2 = bbInt; | ||
| } | ||
| BigBigInt answer = new BigBigInt("0"); | ||
| for (int i = bbInt2.value.length() - 1; i >= 0; i--) { | ||
| int help = 0; | ||
| String ans = ""; | ||
| for (int j = bbInt1.value.length() - 1; j >= 0; j--) { | ||
| help += Integer.parseInt(bbInt2.value.charAt(i) + "") * Integer.parseInt(bbInt1.value.charAt(j) + ""); | ||
| ans = (help % 10) + ans; | ||
|
Owner
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. StringBuilder |
||
| help /= 10; | ||
| } | ||
| ans = Integer.toString(help) + ans; | ||
| for (int j = i; j < bbInt2.value.length() - 1; j++) | ||
| ans = ans + "0"; | ||
| answer = BigBigInt.add(answer, new BigBigInt(ans)); | ||
| } | ||
| return answer; | ||
| } | ||
|
|
||
| static BigBigInt divide(BigBigInt bbInt1, BigBigInt bbInt2) {//Деление двух bbInt | ||
| BigBigInt bbInt; | ||
| if (compare(bbInt1, bbInt2) < 0) { | ||
| bbInt = bbInt1; | ||
| bbInt1 = bbInt2; | ||
| bbInt2 = bbInt; | ||
| } | ||
| bbInt = new BigBigInt("0"); | ||
| String str2; | ||
| String counter = "0"; | ||
| do { | ||
| str2 = add(bbInt, bbInt2).value; | ||
| bbInt = new BigBigInt(str2); | ||
| counter = add(new BigBigInt(counter), new BigBigInt("1")).value; | ||
| } while (compare(bbInt1, bbInt) == 1); | ||
| if (compare(bbInt, bbInt1) == 1) | ||
| counter = subtract(new BigBigInt(counter), new BigBigInt("1")).value; | ||
| return new BigBigInt(counter); | ||
| } | ||
|
|
||
| static BigBigInt remain(BigBigInt bbInt1, BigBigInt bbInt2) {//Остаток от деления двух bbInt | ||
| if ((bbInt1 == new BigBigInt("0")) || (bbInt2 == new BigBigInt("0"))) return new BigBigInt("0"); | ||
| BigBigInt bbInt; | ||
| if (compare(bbInt1, bbInt2) < 0) { | ||
| bbInt = bbInt1; | ||
| bbInt1 = bbInt2; | ||
| bbInt2 = bbInt; | ||
| } | ||
| bbInt = new BigBigInt("0"); | ||
| String str2; | ||
| String counter = "0"; | ||
| do { | ||
| str2 = add(bbInt, bbInt2).value; | ||
| bbInt = new BigBigInt(str2); | ||
| counter = add(new BigBigInt(counter), new BigBigInt("1")).value; | ||
| } while (compare(bbInt1, bbInt) == 1); | ||
| if (compare(bbInt1, bbInt) == 0) return new BigBigInt("0"); | ||
| else { | ||
| bbInt = subtract(bbInt, bbInt2); | ||
| counter = subtract(bbInt1, bbInt).value; | ||
| } | ||
| return new BigBigInt(counter); | ||
| } | ||
|
|
||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,16 +1,36 @@ | ||
| package ru.spbstu.kspt.task1; | ||
|
|
||
| import org.apache.logging.log4j.LogManager; | ||
| import org.apache.logging.log4j.Logger; | ||
|
|
||
| /** | ||
| * Main class | ||
| */ | ||
| import java.util.Scanner; | ||
|
|
||
| public class Main { | ||
| private static final Logger logger = LogManager.getLogger(Main.class); | ||
|
|
||
| public static void main(String[] args) { | ||
| logger.debug("Logging example"); | ||
| System.out.println("Hello World!"); | ||
| public static void main(String[] args){ | ||
| Scanner in = new Scanner(System.in); | ||
| BigBigInt bbInt1; | ||
| BigBigInt bbInt2; | ||
|
|
||
| do { | ||
| System.out.println("Введите ПЕРВОЕ число из интервала [0,+oo]"); | ||
| String string1 = in.nextLine(); | ||
| bbInt1 = new BigBigInt(string1); | ||
| }while (bbInt1.getValue() == null); | ||
|
|
||
| do { | ||
| System.out.println("Введите ВТОРОЕ число из интервала [0,+oo]"); | ||
| String string2 = in.nextLine(); | ||
| bbInt2 = new BigBigInt(string2); | ||
| }while (bbInt2.getValue() == null); | ||
|
|
||
| System.out.println("Первое число: " + bbInt1.getValue()); | ||
| System.out.println("Второе число: " + bbInt2.getValue()); | ||
| System.out.println("Сравнение двух чисел: " + BigBigInt.compare(bbInt1, bbInt2)); | ||
| System.out.println("Сумма двух чисел: " + BigBigInt.add(bbInt1, bbInt2).getValue()); | ||
| System.out.println("Разность двух чисел: " + BigBigInt.subtract(bbInt1, bbInt2).getValue()); | ||
| System.out.println("Произведение двух чисел: " + BigBigInt.multiply(bbInt1, bbInt2).getValue()); | ||
| System.out.println("Деление двух чисел: " + BigBigInt.divide(bbInt1, bbInt2).getValue()); | ||
| System.out.println("Остаток от деления двух чисел: " + BigBigInt.remain(bbInt1, bbInt2).getValue()); | ||
| } | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,17 +1,70 @@ | ||
| package ru.spbstu.kspt.task1; | ||
|
|
||
| import org.junit.jupiter.api.Test; | ||
| import org.apache.logging.log4j.LogManager; | ||
| import org.apache.logging.log4j.Logger; | ||
| import static org.junit.jupiter.api.Assertions.*; | ||
|
|
||
| import static org.junit.jupiter.api.Assertions.assertEquals; | ||
|
|
||
| class MainTest { | ||
| private static final Logger logger = LogManager.getLogger(MainTest.class); | ||
|
|
||
|
|
||
| @Test | ||
| void compare() { | ||
| assertEquals(-1, | ||
| BigBigInt.compare(new BigBigInt("461849213528055328502"), | ||
| new BigBigInt("461849213628055328502"))); | ||
| assertEquals(-1, | ||
| BigBigInt.compare(new BigBigInt(" udsihfs 3798196214 uaoudj21 "), | ||
| new BigBigInt(" 0000 3423248jajklf =12321321"))); | ||
|
|
||
| assertEquals(0, | ||
| BigBigInt.compare(new BigBigInt("9172470126471204862176"), | ||
| new BigBigInt("9172470126471204862176"))); | ||
| assertEquals(0, | ||
| BigBigInt.compare(new BigBigInt(" fusaljfa4378748320023432yo7hfa "), | ||
| new BigBigInt(" fusaljfa4378748320023432yo7hfa "))); | ||
|
|
||
| assertEquals(1, | ||
| BigBigInt.compare(new BigBigInt("763068415235893205639275"), | ||
| new BigBigInt("763068415235893105639275"))); | ||
| assertEquals(1, | ||
| BigBigInt.compare(new BigBigInt(" 743276yuafhsbnamm;of73269432"), | ||
| new BigBigInt("8032-79126147"))); | ||
| } | ||
|
|
||
| @Test | ||
| void add() { | ||
| assertEquals(new BigBigInt("28530940900897641653").getValue(), | ||
| BigBigInt.add(new BigBigInt("2853094012060ufjkaj7840812ijfga"), | ||
| new BigBigInt(" 7802u89jiufsa800841")).getValue()); | ||
| } | ||
|
|
||
| @Test | ||
| void subtract() { | ||
| assertEquals(new BigBigInt("28530939340318039971").getValue(), | ||
| BigBigInt.subtract(new BigBigInt("2853094012060ufjkaj7840812ijfga"), | ||
| new BigBigInt(" 7802u89jiufsa800841")).getValue()); | ||
| } | ||
|
|
||
| @Test | ||
| void multiply() { | ||
| assertEquals(new BigBigInt("22262401584515588627058511722892").getValue(), | ||
| BigBigInt.multiply(new BigBigInt("2853094012060ufjkaj7840812ijfga"), | ||
| new BigBigInt(" 7802u89jiufsa800841")).getValue()); | ||
| } | ||
|
|
||
|
|
||
| @Test | ||
| void divide() { | ||
| assertEquals(new BigBigInt("39652").getValue(), | ||
| BigBigInt.divide(new BigBigInt("3094012060ufjkaj7840812ijfga"), | ||
| new BigBigInt(" 7802u89jiufsa800841")).getValue()); | ||
| } | ||
|
|
||
|
|
||
| @Test | ||
| void exampleTest() { | ||
| logger.info("Test started"); | ||
| assertEquals(10, 10); | ||
| logger.info("Test finished"); | ||
| void remain() { | ||
| assertEquals(new BigBigInt("406444945376").getValue(), | ||
| BigBigInt.remain(new BigBigInt("3094012060ufjkaj78412ijfga"), | ||
| new BigBigInt(" 7802u89jiufsa800841")).getValue()); | ||
| } | ||
| } |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Есть более эффективные способы хранить число.
char- это два байта, в каждомcharпомещается только одна цифра числа.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Вообще, замечание такое же, как и к Сергею - абстрагируйтесь от конкретного типа хранилища данных. То есть ваша бизнес-логика (код, который решает поставленную задачу) не должна знать, как именно вы храните число. Сделайте набор методов по работе с хранилищем (получить i-ую часть числа и т.д.), и пусть логика работает только с этими методами.