Skip to content
Open
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 17 additions & 1 deletion src/main/java/core/basesyntax/FlipBit.java
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,22 @@ public class FlipBit {
* Договоримся, что биты нумеруются от младшего (индекс 1) к старшему (индекс 32).</p>
*/
public int flipBit(int value, int bitIndex) {
return 0;
bitIndex = bitIndex - 1;
StringBuilder stringBuilder = new StringBuilder(Integer.toBinaryString(value));
stringBuilder = stringBuilder.reverse();

if (stringBuilder.length() > bitIndex) {
if (stringBuilder.charAt(bitIndex) == '1') {
stringBuilder.setCharAt(bitIndex, '0');
} else {
stringBuilder.setCharAt(bitIndex, '1');
}
} else {
while (stringBuilder.length() <= bitIndex - 1) {
stringBuilder.append('0');
}
stringBuilder.append('1');
}
return Integer.parseInt(stringBuilder.reverse().toString(), 2);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Now that you know how it works try to do that with ^ and << operators

}
}