I am having trouble with the following excersice.
Write a method starString that accepts an integer parameter n and returns a string of stars (asterisks) 2n long (i.e., 2 to the nth power). For example:
Call Output Reason
starString(0); "*" 2^0 = 1
starString(1); "**" 2^1 = 2
starString(2); "****" 2^2 = 4
starString(3); "********" 2^3 = 8
starString(4); "****************" 2^4 = 16
You should throw an IllegalArgumentException if passed a value less than 0.
I have tried this, but I am looking for a way to multiply the String "*", several times. PD: I can't use .repeat
I am stuck on getting the value of 2 to the n power. As i have tried
int x = (int)Math.pow(2,(n));
but i don't know what to do with that.
public static String starString(int n) {
if(n<0){
throw new IllegalArgumentException("No negative values allowed");
}
if(n==0){
return "*";
}else{
return starString(0) + starString(n-1);
}
}
test #1:starString(0)
return:"*"
result: pass
test #2:starString(1)
return:"**"
result: pass
test #3:starString(2)
expected return:"****"
your return:"***"
result: fail
test #4:starString(3)
expected return:"********"
your return:"****"
result: fail
test #5:starString(4)
expected return:"****************"
your return:"*****"
result: fail
test #6:starString(-1)
exp. exception:IllegalArgumentException
your exception:IllegalArgumentException on line 3: No negative values allowed
result: pass
This will work, although it will blow up for large n.
public static String starString(int n) {
if(n<0){
throw new IllegalArgumentException("No negative values allowed");
}
if(n==0){
return "*";
}else{
return starString(n-1) + starString(n-1);
}
}
obviously you can get 2^n using
public static int twoToN(int n) {
if(n<0){
throw new IllegalArgumentException("No negative values allowed");
}
if(n==0){
return 1;
}else{
return 2* twoToN(n-1);
}
}
You could do something like this
public static void main(String[] args) {
int count = (int)Math.pow(2, 4);
System.out.println(count);
String value = starString(count);
System.out.println(value);
System.out.println(value.length());
}
static String starString(int n) {
String result = "";
if (n > 0) {
result = "*" + starString(n -1);
}
return result;
}
Try this :
public static String starString(int n) {
if (n < 0) {
throw new IllegalArgumentException("No negative values allowed");
}
if (n == 0) {
return "*";
} else {
int pow = (int) Math.pow(2, n);
int pow2 = pow / 2;
int starsCount = pow - pow2;
StringBuilder stringBuilder = new StringBuilder();
IntStream.iterate(0, operand -> operand + 1)
.limit(starsCount)
.forEach(value -> stringBuilder.append("*"));
return stringBuilder.toString() + starString(n - 1);
}
}
In every recursive step I count how many stars have to be appended (pow - pow2).
An important optimization that can help with expensive function calls such as this is memoization; if you start with a table containing one star for the case of zero and then populate the table as you return output(s) the output does not need to be re-computed for every step. Like,
private static Map<Integer, String> memo = new HashMap<>();
static {
memo.put(0, "*");
}
public static String starString(int n) {
if (n < 0) {
throw new IllegalArgumentException("No negative values allowed");
} else if (!memo.containsKey(n)) {
final String pre = starString(n - 1);
StringBuilder sb = new StringBuilder(pre.length() * 2);
sb.append(pre).append(pre);
memo.put(n, sb.toString());
}
return memo.get(n);
}
Then you can print each line (and count the stars) like
public static void main(String[] args) {
for (int i = 0; i < 8; i++) {
String s = starString(i);
System.out.printf("%d: %s%n", s.length(), s);
}
}
Which outputs
1: *
2: **
4: ****
8: ********
16: ****************
32: ********************************
64: ****************************************************************
128: ********************************************************************************************************************************
Related
I need to create an algorithm for String decomposition.
Some examples:
ABCABCDEDEDEF --> ABC*2+DE*3+F
ABCcABCczcz --> ABC*2+cz*2+c
test --> test
Each segment of the string should be seperated by a + and, if repeated, followed up by a * plus the number of times it appears in succession.
This is what I have tried:
private static int[] prefixFunction(String source) {
int n = source.length();
int[] pi = new int[n];
for (int i = 1; i < n; i++) {
int j = pi[i - 1];
while (j > 0 && source.charAt(i) != source.charAt(j))
j = pi[j - 1];
if (source.charAt(i) == source.charAt(j))
j++;
pi[i] = j;
}
return pi;
}
This solution keeps everything in order, meaning an input like ABCABCDEDEDEF will return ABC*2+DE*3+F or an input like abDEDEab will return ab+DE*2+ab.
If you don't keep the order, it will be impossible to reconstruct the String later with 100 % accuracy.
public static void main(String[] args) {
String input = "ABCABCDEDEDEF";
String output = findDecomposition(input);
System.out.println("Output: " + output);
}
public static String findDecomposition(String input) {
String substring = input;
StringBuilder builder = new StringBuilder();
for (int start = 0, count = 1; start < input.length(); start++, count = 1) {
for (int end = start + 1; end < input.length(); end++) {
substring = input.substring(start, end);
while (true) {
String next = input.substring(start + substring.length(), Math.min(end + substring.length(), input.length()));
if (next.equals(substring)) {
count++;
start += substring.length();
end += substring.length();
} else
break;
}
if (count > 1) {
start += substring.length() - 1;
break;
}
}
if (count > 1) {
if (builder.length() > 0 && builder.charAt(builder.length() - 1) != '+')
builder.append('+');
builder.append(substring + "*" + count + "+");
} else
builder.append(input.charAt(start));
}
String result = builder.toString();
if (result.endsWith("+"))
return result.substring(0, result.length() - 1);
else
return result;
}
THe brute force alghoritm can work as follows.
Prerequisities:
First letter is set as root
Data structure of each possible solution is linked list. Value of each node is text to be written.
When outputting solution, first put to Map all text values together with number of appereances. If it appears more than once, use * as multiplicator
Example: One of the solution looks like this ABC-C-ABC, the output will be ABC*2+C
Solution:
Take next letter from input
New solutions are based on existing solutions. Each new solution is old solution + new letter added in one of the existing nodes or as single letter in new node.
Save new solutions as existing solutions.
Repeat from 1 until you process all letters
Calculate value of all solutions and select one with lowest string characters
I added example, as you can see the number of solutions are increasing quickly so it is not fully finished for all 6 letters. Each step represent the cycle from 1. to 4., you can see that in each step the previous solutions are used as base for new solutions. There are multiple new solutions created for each existing solution.
This code returns the following compositions:
ABCABCDEDEDEF -> ABC*2+DE*3+F
ABCcABCczcz -> ABCc*2+zcz
cefABCcABCczcz -> cef+ABCc*2+zcz
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
public class Decomposition {
public static void main(String[] args) {
Decomposition d = new Decomposition("ABCABCDEDEDEF");
System.out.println(d.getOptimalDecomposition());// Output: ABC*2+DE*3+F
d = new Decomposition("ABCcABCczcz");
System.out.println(d.getOptimalDecomposition());// Output: ABCc*2+zcz
d = new Decomposition("cefABCcABCczcz");
System.out.println(d.getOptimalDecomposition());// Output: cef+ABCc*2+zcz
}
private List> decompositions;
private String toDecompose;
public Decomposition(String toDecompose) {
decompositions = new ArrayList();
this.toDecompose = toDecompose;
}
public String getOptimalDecomposition() {
decompose(0, new ArrayList());
return calculateOptimal(convertToPartsMap());
}
private String calculateOptimal(List> partsCount) {
Collections.sort(partsCount, new SortDecompositions());
StringBuilder optimal = new StringBuilder();
for (int i = 0; i 1) {
optimal.append("*");
optimal.append(pc.count);
}
if (i != partsCount.get(0).size() - 1) {
optimal.append("+");
}
}
return optimal.toString();
}
private List> convertToPartsMap() {
List> partsMap = new ArrayList();
for (List parts : decompositions) {
List partsCount = new ArrayList();
String lastPart = null;
int curCount = 0;
for (int i = 0; i parts) {
if (nextChar == toDecompose.length()) {
decompositions.add(parts);
return;
}
char toAdd = toDecompose.charAt(nextChar);
if (parts.isEmpty()) {
parts.add("" + toAdd);
decompose(nextChar + 1, parts);
} else {
// left
List leftParts = parts.stream().collect(Collectors.toList());// shallow copy
if (!leftParts.isEmpty()) {
int last = leftParts.size() - 1;
leftParts.set(last, leftParts.get(last) + toAdd);
} else {
leftParts.add("" + toAdd);
}
// right
List rightParts = parts.stream().collect(Collectors.toList());// shallow copy
rightParts.add("" + toAdd);
decompose(nextChar + 1, leftParts);
decompose(nextChar + 1, rightParts);
}
}
}
class PartCount {
String part;
int count;
public PartCount(String part, int count) {
this.part = part;
this.count = count;
}
#Override
public String toString() {
return "[" + part + ", " + count + "]";
}
}
class SortDecompositions implements Comparator> {
public int compare(List a, List b) {
// Here you can define what exactly means "taking up least space".
return countChars(a) - countChars(b);
}
private int countChars(List listPc) {
int count = 0;
for (PartCount pc : listPc) {
count += pc.part.length();
}
return count;
}
}
This can be solved by using KMP alogorthm longest prefix which is also suffix
Steps:
iterate the string "ABCABCDEDEDEF" and construct lps array for the string. The values in the array will be
0 0 0 1 2 3 0 0 0 0 0 0 0
This lps array gives the number of times the prefix is repeated in the string.
In the above case it is repeated only one time. Considering the actual prefix number of times will be 2 it becomes ABC*2
Take the substring of the remaining string and repeat the step 1 till the end of the string.
I can provide you the code if needed. The worst time complexity will be O(n2)
So I have a question that asks me to write a method that is passed a String consisting of digits, and this method should return the sum of those digits. So if the String is "123" my method should return the value 6. If the null String is passed, my method should return zero. It asks me to use Recursion. Here's what I have so far:
public class Q2 {
public static void main(String[] args) {
String s = "135";
System.out.println(sumDig(s));
}
public static String sumDig(int num)
{
int i = Integer.parseInt(num);
int sum = 0;
if (i == 0)
return sum;
int sum = num%10 + sumDig(num/10);
return sum;
}
}
I'm just having a bit of trouble trying to see if I'm on the right track, I know it's totally wonky and recursion is still really odd to me so any help is really appreciated. Thank you!
Edit: I don't think this is a duplicate of any other problems asking how to find sum of digits using recursion, this is very similar but it's different because it asks to find sum of digits from a String.
The key issue that folks are pointing out is that you've inverted your method signature:
public static String sumDig(int num)
which should be:
public static int sumDig(String num)
Let's also address another issue in that you took data that you could process directly, made it into something else more complicated, and processed that instead. Let's operate directly on what you are handed:
public class Q2 {
public static int sumDig(String digits) {
int sum = 0;
if (! digits.isEmpty()) {
sum += Character.getNumericValue(digits.charAt(0)) + sumDig(digits.substring(1));
}
return sum;
}
public static void main(String[] args) {
System.out.println(sumDig(args[0]));
}
}
USAGE
% java Q2 123
6
%
In the comments below I want you to see the logical and syntactical mistakes you made:
public static String sumDig(int num) {
// the return type should be int and not String
// the parameter num should be String and not int
int i = Integer.parseInt(num);
int sum = 0;
if (i == 0)
return sum;
int sum = num%10 + sumDig(num/10);
// sum has been previously declared as int, so int is not required in the above line
// the number is i and this should be used and not num (which is a String)
// in the calculations
// num/10 cannot be used as a parameter of sumDig because sumDig needs
// a String parameter
return sum;
}
This does not mean that if you make all the proposed corrections that the method will work as expected. For example what happens when the string is null, etc?
// TODO not working with negative numbers
public static int sumDig(String str) {
return str.isEmpty() ? 0 : str.charAt(0) - '0' + sumDig(str.substring(1));
}
public static int sumDig(int num) {
return Math.abs(num) < 10 ? Math.abs(num) : (Math.abs(num) % 10 + sumDig(num / 10));
}
These are three variations of recursive methods, differing by parameter and return type but they all do the same job of adding input number and printing the output.
// Recursive method where parameter is int and return type String
public static String getSumStr(int n) {
n = n < 0 ? -n : n; // takes care of negative numbers
if (n < 10) {
return String.valueOf(n);
}
return String.valueOf(n % 10 + Integer.parseInt(getSumStr(n / 10)));
}
// Recursive method where parameter and return type both are int
public static int getSum(int n) {
n = n < 0 ? -n : n; // takes care of negative numbers
return n < 10 ? n : (n % 10 + getSum(n / 10));
}
// Recursive method where parameter and return type both are String
public static String getSumStr(String s) {
if (s == null || s.length() == 0) {
return "0";
}
if (s.length() == 1) {
return s;
}
return String.valueOf(Integer.parseInt(s.substring(0, 1))
+ Integer.parseInt(getSumStr(s.substring(1, s.length()))));
}
Assuming the String is all digits, the below works with String of length longer than Integer.MAX_VALUE
public static void main(String[] args) {
String s = "123344566777766545";
long i = sumDig(s);
System.out.println(i);
}
public long sumDig(String s) {
return sumDigits(s.toCharArray(), 0);
}
public long sumDigits(char[] chars, int index) {
if (index == chars.length - 1) {
return chars[index] - '0';
}
return sumDigits(chars, index + 1) + (chars[index] - '0');
}
I'll give you a hint: what would happen if you did a for loop over the characters in the string and added the digits up that way? I'd suggest trying to write such a for loop. Here's an example of what I'm talking about (with apologies for it being in C# rather than Java - the syntax is very similar, though):
string s = "123";
int sum = 0;
for (int i = 0; i < s.Length; i++)
{
sum += int.Parse(s[i].ToString());
}
After that, how would you write a recursive function that's equivalent to the for loop?
The scenario is - I read the last line of a file, increment it by one and write it back.
The read and write has been done. I am finding it difficult to increment the alpha-numberic values as it has a few conditions.
The conditions are:
It should only be 3 characters long
Example : A01, A02.... A99, B01, B02.... B99..
Once Z99 is reached it should be AA1, AA2, AA3...AA9, .....
Then AB1, AB2,... AZ9
So basically while incrementing the value should not go AA10 which makes it 4 characters
What I am doing now is separating the alphabets and integers, incrementing it and concatenating them back.
The code so far:
String[] part = lastLine.split("(?<=\\D)(?=\\d)");
System.out.println(part[0]);
System.out.println(part[1]);
int numberOnly = Integer.parseInt(lastLine.replaceAll("[^0-9]", ""));
numberOnly++;
String lettersOnly = lastLine.replaceAll("[^A-Z]", "");
if (lettersOnly.length() > 1){
String lastLetter = lettersOnly.substring(lettersOnly.length() - 1);
if(lastLetter.equalsIgnoreCase("Z") && number.equalsIgnoreCase("9") ){
String notLastLetter = lettersOnly.substring(lettersOnly.length() - 2);
char d = lettersOnly.charAt(0);
d++;
System.out.println("Letters after increment more tan two : " +d);
lettersOnly = Character.toString(d) + "Z";
}
}
else{
}
System.out.println("Letters after increment : " +lettersOnly);
Any help would be greatly appreciated.
public class AlphaNumericCounter {
String[] part;
int counter; //Variable storing numeric part of counter
String alpha; //Variable storing Alpha part of counter
static String final_output = "A00"; // First Input considered as A00 and also the variable which will be store each count
static boolean continueIncrement = true; //For running the loop till we reach ZZ9
/* Def constructor */
public AlphaNumericCounter() {
}
/* Constructor called from main method with primary input A00 */
public AlphaNumericCounter(String number) {
part = number.split("(?<=\\D)(?=\\d)");
}
/* Function called each time from inside loop to generate next alphanumeric count */
public void increment() {
part = final_output.split("(?<=\\D)(?=\\d)");
counter = Integer.valueOf(part[1]) + 1;
alpha = part[0];
}
public String toString() {
if (alpha.length() == 1){
if (String.valueOf(counter).length() > 2){
if ((int)alpha.charAt(0) + 1 > 90/*If Z encountered*/){
alpha = "AA";
}else{
alpha = String.valueOf((char)((int)alpha.charAt(0) + 1));//Take Next Alphabet
}
counter = 1; //Reset counter to 1
}
}else{
//We have AA, AB ... ZZ format of alpha
if (String.valueOf(counter).length() > 1){
if ((int)alpha.charAt(0) + 1 > 90 && (int)alpha.charAt(1) + 1 > 90){
continueIncrement = false;
System.out.println("NO MORE COMBINATION AVAILABLE"); //We reached ZZ
return "";
}else if ((int)alpha.charAt(1) + 1 <= 90){
alpha = String.valueOf((char)((int)alpha.charAt(0))) + String.valueOf((char)((int)alpha.charAt(1) + 1));
counter = 1;
}else if ((int)alpha.charAt(1) + 1 > 90){
if ((int)alpha.charAt(0) + 1 <= 90){
alpha = String.valueOf((char)((int)alpha.charAt(0) + 1)) + "A";
counter = 1;
}
}
}
}
generateString();
return final_output;
}
private void generateString(){
int l1 = String.valueOf(counter).length();
int l2 = alpha.length();
final_output = alpha + (l2 == 1 && l1 == 1 ? "0" : "") + String.valueOf(counter);
}
public static void main(String[] args) {
AlphaNumericCounter lic = new AlphaNumericCounter(final_output);
while (continueIncrement){
lic.increment();
System.out.println(lic);
}
}
}
What about incrementing each "digit" separatly from right to left and handle overvlow to the next digit:
String number;//number - is your originally string
char[] digits = number.toCharArray();
boolean overflow = true;
for(int i = 2; i >= 0; i--){
if(overflow){
switch(digits[i]){
case 'Z':
digits[i] = '0';
overflow = true;
break;
case '9':
digits[i] = 'A';
overflow = false;
break;
default:
digits[i]++;
overflow = false;
}
}
}
if(overflow){
//handle ZZZ overflow here
}
String result = new String(digits);
A simple solution is to count in Base36
Try this:
class AlphaNumericIncrementer {
public static void main(String[] args) {
/*
When starting at '000' => We hit 'zzz' (i.e. Dead End) at 46,656
When starting at 'A00' => We hit 'zzz' (i.e. Dead End) at 33,696
*/
int index = 0;
String currentNumber = "000";
while (index < 46656) {
index++;
String incrementedNumber = base36Incrementer(currentNumber, 36);
currentNumber = incrementedNumber;
if (incrementedNumber.toCharArray().length != 3) {
System.out.println("We got intruder with length: " + incrementedNumber.toCharArray().length);
System.out.println("Our Intruder is: " + incrementedNumber);
break;
}
System.out.println(incrementedNumber);
}
System.out.println("Number of entries: " + index);
}
// The function that increments current string
public static String base36Incrementer(String v, int targetBase) {
String answer = Integer.toString(Integer.parseInt(v, targetBase) + 1, targetBase);
return String.format("%3s", answer).replace(' ', '0');
}
}
Hey Guys I'm having a problem when I run my program. In the PostfixEvaluate() Method is where it takes in a string and solves the postfix problem and returns it. Well when I go to run it, I'm getting a bunch of random numbers(some repeated), I'm going crazy because I don't know what else to try and I've spent more time on this than it should normally take.
Heres the PostfixEvaluate Method:
public int PostfixEvaluate(String e){
//String Operator = "";
int number1;
int number2;
int result=0;
char c;
//number1 = 0;
//number2 = 0;
for(int j = 0; j < e.length(); j++){
c = e.charAt(j);
if (c != '+'&& c!= '*' && c!= '-' && c!= '/') {
//if (c == Integer.parseInt(e)) {
s.push(c);
}
else {
number1 = s.pop();
number2 = s.pop();
switch(c) {
case '+':
result = number1 + number2;
break;
case '-':
result = number1 - number2;
break;
case '*':
result = number1 * number2;
break;
case '/':
result = number1 / number2;
break;
} s.push(result);
}
System.out.println(result);
}
return s.pop();
}
public static void main(String[] args) {
Stacked st = new Stacked(100);
String y = new String("(z * j)/(b * 8) ^2");
String x = new String("2 3 + 9 *");
TestingClass clas = new TestingClass(st);
clas.test(y);
clas.PostfixEvaluate(x);
}
}
This is the Stack Class:
public class Stacked {
int top;
char stack[];
int maxLen;
public Stacked(int max) {
top = -1;
maxLen = max;
stack = new char[maxLen];
}
public void push(int result) {
top++;
stack[top] = (char)result;
}
public int pop() {
int x;
x = stack[top];
//top = top - 1;
top--;
return x;
}
public boolean isStackEmpty() {
if(top == -1) {
System.out.println("Stack is empty " + "Equation Good");
return true;
}
else
System.out.println("Equation is No good");
return false;
}
public void reset() {
top = -1;
}
public void showStack() {
System.out.println(" ");
System.out.println("Stack Contents...");
for(int j = top; j > -1; j--){
System.out.println(stack[j]);
}
System.out.println(" ");
}
public void showStack0toTop() {
System.out.println(" ");
System.out.println("Stack Contents...");
for(int j=0; j>=top; j++){
System.out.println(stack[j]);
}
System.out.println(" ");
}
}
It looks to me like you aren't handling spaces at all.
This means that when you put in a space, it is implicitly converting the character space to the ascii value of it (32) when it pops it off the stack during an operation. Also, it looks like you are assuming that all numbers/results will be single digit, and casting from char to int, which is not what you want to do, since that will convert the char to the ascii value of the char, ' ' -> 32, '3' -> 51, etc.
If I were you, I would do this for your loop in PostfixEvaluate:
while(!e.equals("")){
string c;
int space = e.indexOf(' ');
if(space!=-1){
c = e.substring(0,space);
e = e.substring(space+2);
} else{
c = e;
e = "";
}
if (!c.equals("+")&& !c.equal("*") && !c.equals("-") && !c.equals("/")) {
//...
}
and change your stack to hold strings or ints.
The problem is that you are pushing char onto a stack as an int, so you are unintentionally working with the ascii representations of numbers, which is not the actual value of the number.
Instead of this complicated character walking, tokenize the input string using String.split(). Example:
String[] tokens = e.split(" ");
for(String token:tokens){
if (!"+".equals(token) && !"*".equals(token) && !"-".equals(token) && !"/".equals(token)) {
s.push(Integer.parseInt(token));
} else {
....
}
}
You need to split the string into tokens first:
/* Splits the expression up into several Strings,
* all of which are either a number or and operator,
* none of which have spaces in them. */
String [] expressionAsTokens = e.split(" ");
Then you need to make sure you compare Strings, not chars:
//compare strings instead of chars
String token = expressionAsTokens[j];
if (!"+".equals(token) && !"*".equals(token) && !"-".equals(token) && !"/".equals(token)) {
s.push(Integer.parseInt(token));
} else {
//same code as you had before
}
Also, is there any reason you are storing everything as a char array in your Stacked class? Your pop() method returns and integer, yet everything is stored as a char.
For this application, everything should be stored as an integer:
public class Stacked {
int stack[]; // array is of type integer
int top;
int maxLen;
// constructor
public void push() {/*...*/}
public int pop() {/*...*/} //pop returns an int as before
//...
}
One final note: Be careful what order you add and subtract the numbers in. I don't remember if postfix operands are evaluated left first or right first, but make sure you get them in the right order. As you have it now, 2 3 - 4 * would evaluate as 4 * (3 - 2) and I think it should be (2 - 3) * 4. This won't matter with adding and multiplying, but it will with subtracting and dividing.
What would be the best way (ideally, simplest) to convert an int to a binary string representation in Java?
For example, say the int is 156. The binary string representation of this would be "10011100".
Integer.toBinaryString(int i)
There is also the java.lang.Integer.toString(int i, int base) method, which would be more appropriate if your code might one day handle bases other than 2 (binary). Keep in mind that this method only gives you an unsigned representation of the integer i, and if it is negative, it will tack on a negative sign at the front. It won't use two's complement.
public static string intToBinary(int n)
{
String s = "";
while (n > 0)
{
s = ( (n % 2 ) == 0 ? "0" : "1") +s;
n = n / 2;
}
return s;
}
One more way- By using java.lang.Integer you can get string representation of the first argument i in the radix (Octal - 8, Hex - 16, Binary - 2) specified by the second argument.
Integer.toString(i, radix)
Example_
private void getStrtingRadix() {
// TODO Auto-generated method stub
/* returns the string representation of the
unsigned integer in concern radix*/
System.out.println("Binary eqivalent of 100 = " + Integer.toString(100, 2));
System.out.println("Octal eqivalent of 100 = " + Integer.toString(100, 8));
System.out.println("Decimal eqivalent of 100 = " + Integer.toString(100, 10));
System.out.println("Hexadecimal eqivalent of 100 = " + Integer.toString(100, 16));
}
OutPut_
Binary eqivalent of 100 = 1100100
Octal eqivalent of 100 = 144
Decimal eqivalent of 100 = 100
Hexadecimal eqivalent of 100 = 64
public class Main {
public static String toBinary(int n, int l ) throws Exception {
double pow = Math.pow(2, l);
StringBuilder binary = new StringBuilder();
if ( pow < n ) {
throw new Exception("The length must be big from number ");
}
int shift = l- 1;
for (; shift >= 0 ; shift--) {
int bit = (n >> shift) & 1;
if (bit == 1) {
binary.append("1");
} else {
binary.append("0");
}
}
return binary.toString();
}
public static void main(String[] args) throws Exception {
System.out.println(" binary = " + toBinary(7, 4));
System.out.println(" binary = " + Integer.toString(7,2));
}
}
This is something I wrote a few minutes ago just messing around. Hope it helps!
public class Main {
public static void main(String[] args) {
ArrayList<Integer> powers = new ArrayList<Integer>();
ArrayList<Integer> binaryStore = new ArrayList<Integer>();
powers.add(128);
powers.add(64);
powers.add(32);
powers.add(16);
powers.add(8);
powers.add(4);
powers.add(2);
powers.add(1);
Scanner sc = new Scanner(System.in);
System.out.println("Welcome to Paden9000 binary converter. Please enter an integer you wish to convert: ");
int input = sc.nextInt();
int printableInput = input;
for (int i : powers) {
if (input < i) {
binaryStore.add(0);
} else {
input = input - i;
binaryStore.add(1);
}
}
String newString= binaryStore.toString();
String finalOutput = newString.replace("[", "")
.replace(" ", "")
.replace("]", "")
.replace(",", "");
System.out.println("Integer value: " + printableInput + "\nBinary value: " + finalOutput);
sc.close();
}
}
Convert Integer to Binary:
import java.util.Scanner;
public class IntegerToBinary {
public static void main(String[] args) {
Scanner input = new Scanner( System.in );
System.out.println("Enter Integer: ");
String integerString =input.nextLine();
System.out.println("Binary Number: "+Integer.toBinaryString(Integer.parseInt(integerString)));
}
}
Output:
Enter Integer:
10
Binary Number: 1010
The simplest approach is to check whether or not the number is odd. If it is, by definition, its right-most binary number will be "1" (2^0). After we've determined this, we bit shift the number to the right and check the same value using recursion.
#Test
public void shouldPrintBinary() {
StringBuilder sb = new StringBuilder();
convert(1234, sb);
}
private void convert(int n, StringBuilder sb) {
if (n > 0) {
sb.append(n % 2);
convert(n >> 1, sb);
} else {
System.out.println(sb.reverse().toString());
}
}
Using built-in function:
String binaryNum = Integer.toBinaryString(int num);
If you don't want to use the built-in function for converting int to binary then you can also do this:
import java.util.*;
public class IntToBinary {
public static void main(String[] args) {
Scanner d = new Scanner(System.in);
int n;
n = d.nextInt();
StringBuilder sb = new StringBuilder();
while(n > 0){
int r = n%2;
sb.append(r);
n = n/2;
}
System.out.println(sb.reverse());
}
}
here is my methods, it is a little bit convince that number of bytes fixed
private void printByte(int value) {
String currentBinary = Integer.toBinaryString(256 + value);
System.out.println(currentBinary.substring(currentBinary.length() - 8));
}
public int binaryToInteger(String binary) {
char[] numbers = binary.toCharArray();
int result = 0;
for(int i=numbers.length - 1; i>=0; i--)
if(numbers[i]=='1')
result += Math.pow(2, (numbers.length-i - 1));
return result;
}
Using bit shift is a little quicker...
public static String convertDecimalToBinary(int N) {
StringBuilder binary = new StringBuilder(32);
while (N > 0 ) {
binary.append( N % 2 );
N >>= 1;
}
return binary.reverse().toString();
}
if the int value is 15, you can convert it to a binary as follows.
int x = 15;
Integer.toBinaryString(x);
if you have the binary value, you can convert it into int value as follows.
String binaryValue = "1010";
Integer.parseInt(binaryValue, 2);
This can be expressed in pseudocode as:
while(n > 0):
remainder = n%2;
n = n/2;
Insert remainder to front of a list or push onto a stack
Print list or stack
You should really use Integer.toBinaryString() (as shown above), but if for some reason you want your own:
// Like Integer.toBinaryString, but always returns 32 chars
public static String asBitString(int value) {
final char[] buf = new char[32];
for (int i = 31; i >= 0; i--) {
buf[31 - i] = ((1 << i) & value) == 0 ? '0' : '1';
}
return new String(buf);
}
My 2cents:
public class Integer2Binary {
public static void main(String[] args) {
final int integer12 = 12;
System.out.println(integer12 + " -> " + integer2Binary(integer12));
// 12 -> 00000000000000000000000000001100
}
private static String integer2Binary(int n) {
return new StringBuilder(Integer.toBinaryString(n))
.insert(0, "0".repeat(Integer.numberOfLeadingZeros(n)))
.toString();
}
}
This should be quite simple with something like this :
public static String toBinary(int number){
StringBuilder sb = new StringBuilder();
if(number == 0)
return "0";
while(number>=1){
sb.append(number%2);
number = number / 2;
}
return sb.reverse().toString();
}
public class BinaryConverter {
public static String binaryConverter(int number) {
String binary = "";
if (number == 1){
binary = "1";
return binary;
}
if (number == 0){
binary = "0";
return binary;
}
if (number > 1) {
String i = Integer.toString(number % 2);
binary = binary + i;
binaryConverter(number/2);
}
return binary;
}
}
In order to make it exactly 8 bit, I made a slight addition to #sandeep-saini 's answer:
public static String intToBinary(int number){
StringBuilder sb = new StringBuilder();
if(number == 0)
return "0";
while(number>=1){
sb.append(number%2);
number = number / 2;
}
while (sb.length() < 8){
sb.append("0");
}
return sb.reverse().toString();
}
So now for an input of 1 you get an output of 00000001
public static String intToBinaryString(int n) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 32 && n != 0; i++) {
sb.append((n&1) == 1 ? "1" : "0");
n >>= 1;
}
return sb.reverse().toString();
}
We cannot use n%2 to check the first bit, because it's not right for negtive integer. We should use n&1.