JAVA - Generate 5 digits code using Math.random() - java

I'm writing a short program which be able to generate 5 digits code mixed with 0-9, a-z, A-Z.
This is my code:
import java.util.*;
public class FiveDigitsRandom
{
public static void main(String[] args)
{
new FiveDigitsRandom().use();
}
public void use()
{
char choice;
while((choice=readChar()) != 'x')
{
switch(choice)
{
case'n':
generateAll();
break;
}
}
}
public char readChar()
{
System.out.print("Please choose n/x: ");
Scanner scanner = new Scanner(System.in);
return scanner.nextLine().charAt(0);
}
public void generateAll()
{
String[]code = new String[5];
for(int i=0; i<code.length; i++)
{
int random = generate0_2();
switch(random)
{
case 0:
code[i] = generate0_9();
break;
case 1:
code[i] = generate_a_z();
break;
case 2:
code[i] = generate_A_Z();
break;
}
}
for(int j=0; j<code.length; j++)
{
System.out.print(code[j]);
}
System.out.println(" ");
}
public int generate0_2()
{
return (int)Math.random()*3;
}
public String generate0_9()
{
int a = (int)(Math.random() * 10);
String AA = Integer.toString(a);
return AA;
}
public String generate_a_z()
{
char a = (char)((int)'a'+ Math.random() * ((int)'z' - (int)'a' + 1));
String AA = Character.toString(a);
return AA;
}
public String generate_A_Z()
{
char a = (char)((int)'A'+ Math.random() * ((int)'Z' - (int)'A' + 1));
String AA = Character.toString(a);
return AA;
}
}
It suppose to generate a random code as 0AzhG, Hg78N. But now I can only have 5 digits code with random number 0-9. Please tell me where is wrong in my code??
Thank you!

Your generate0_2 method is wrong.
public int generate0_2()
{
return (int)Math.random()*3;
}
When you cast it to int, it works like ((int)Math.random)*3 which means, it provides 0 every time.
change it to
public int generate0_2()
{
return (int)(Math.random()*3);
}

A problem you have is that your won't have an even distribution. i.e. individual digits are more likely than individual letters. One way to have an even distribution is you have an even function.
public static char randomChar() {
// random.nextInt(62) would be faster.
int n = (int) (Math.random() * 62);
if (n < 10) return (char) ('0' + n);
n -= 10;
if (n < 26) return (char) ('A' + n);
n -= 26;
return (char) ('a' + n);
}
public static String randomString(int length) {
char[] chars = new char[length];
for (int i = 0; i < length; i++)
char[i] = randomChar();
return new String(chars);
}

Maybe it's easely to use RandomStringUtils
import org.apache.commons.lang3.RandomStringUtils;
class Main {
public static void main(String[] args) {
// Prints only A-Z, a-z, 0-9
System.out.println(RandomStringUtils.randomAlphabetic(5));
// Prints only A-Z, a-z
System.out.println(RandomStringUtils.randomAlphanumeric(5));
}
}

Related

Finding Kaprekars Constant of a number using Java

So I had tried this online challenge but got runtime error.Please help.I am new to programming. I have attached the problem statement and my solution.
The Challenge
Using the Java language, have the function KaprekarsConstant(num) take an integer of four digits (with at least two being distinct) and perform the following routine on said number:
Arrange the digits in descending order and in ascending order.
Subtract the smaller number from the bigger number, padding the difference with zeroes if necessary to maintain a four-digit number.
Then repeat step 1 and 2 using the four-digit difference.
Stop when the difference of the two, permuted numbers equals 6174.
Return the number of times that you had to perform steps 1 and 2 before arriving at a difference with the value of 6174.
nb: performing the routine on 6174 will always give you 6174 (7641 - 1467 = 6174).
For example: if num is 3524 your program should return 3: (pass 1) 5432 - 2345 = 3087, (pass 2) 8730 - 0378 = 8352, (pass 3) 8532 - 2358 = 6174.
Here is my solution:
import java.util.*;
import java.io.*;
class Main {
public static int KaprekarsConstant(int num) {
int diff = 0, count = 0;
while (diff != 6174) {
String s1 = String.valueOf(num);
int[] ch1 = new int[s1.length()];
for (int i = 0; i < ch1.length; i++) {
ch1[i] = s1.charAt(i);
}
Arrays.sort(ch1);
String s2 = String.valueOf(ch1);
String s3 = "";
for (int j = s2.length() - 1; j >= 0; j++) {
s3 += s2.charAt(j);
}
int a = Integer.parseInt(s2);
int b = Integer.parseInt(s3);
if (a > b) {
diff = a - b;
} else if (b > a) {
diff = b - a;
} else {
System.out.println("goal cant be reached");
break;
}
count++;
num = diff;
}
return num;
}
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.print(KaprekarsConstant(s.nextLine()));
}
}
Try this code:
/**
* KaprekarConstant
*/
import java.util.InputMismatchException;
import java.util.Scanner;
import java.util.Arrays;
import java.util.Collections;
public class KaprekarConstant {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int inputNumber;
char[] digits;
System.out.print("Enter four digit number: ");
try {
inputNumber = scan.nextInt();
if (checkLength(inputNumber))
throw new Exception();
Kaprekar(inputNumber);
} catch (InputMismatchException e) {
System.out.println("Not a number");
} catch (Exception ex) {
System.out.println("Number must have four digits");
} finally {
scan.close();
}
}
public static void Kaprekar(int target) {
int maximum = 0, minimum = 0, result = 0;
Integer[] digits = new Integer[4];
if (target == 6174)
return;
int i = 0;
while (i < 4) {
digits[i] = target % 10;
target /= 10;
i++;
}
Arrays.sort(digits);
minimum = toInt(digits);
Arrays.sort(digits, Collections.reverseOrder());
maximum = toInt(digits);
result = maximum - minimum;
System.out.println(String.format("%d - %d = %d", maximum, minimum, result));
Kaprekar(result);
}
public static boolean checkLength(int number) {
if (String.valueOf(number).length() < 5 && String.valueOf(number).length() > 3)
return false;
return true;
}
public static int toInt(Integer[] digits) {
int number = 0;
for (int digit : digits) {
number *= 10;
number += digit;
}
return number;
}
}
I think this is best method to find the karpekar constant.
There were some basic syntax & logical errors in your code. I have made appropriate changes in it. See if you understand it.
import java.util.*;
import java.io.*;
public class Main {
public static int KaprekarsConstant(int num) {
int diff = 0, count = 0;
while (diff != 6174) {
String s1 = String.valueOf(num);
char[] ch1 = new char[s1.length()];
for (int i = 0; i < ch1.length; i++) {
ch1[i] = s1.charAt(i);
}
Arrays.sort(ch1);
String s2 = new String(ch1);
String s3 = "";
for (int j = s2.length() - 1; j >= 0; j--) {
s3 += s2.charAt(j);
}
int a = Integer.parseInt(s2);
int b = Integer.parseInt(s3);
if (a > b) {
diff = a - b;
} else if (b > a) {
diff = b - a;
} else {
System.out.println("goal cant be reached");
break;
}
count++;
num = diff;
}
return count;
}
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.print(KaprekarsConstant(s.nextInt()));
}
}
This solution has less lines of code:
import static java.lang.System.out;
import java.util.Arrays;
/**
* #see https://en.wikipedia.org/wiki/6174_%28number%29
*/
public class KaprekarConstant {
public static void main(String[] args) {
assert(count(3524) == 3);
assert(count(3087) == 2);
assert(count(8352) == 1);
assert(count(6174) == 1);
out.println("All passed.");
}
public static int count(int start) {
int ct = 0;
do {
start = calc(start);
ct++;
} while (start != 6174);
return ct;
}
static int calc(int n) {
String n1s = String.format("%04d", n);
char[] chs = n1s.toCharArray();
Arrays.sort(chs);
n1s = new String(chs);
String n2s = new StringBuilder(new String(n1s)).reverse().toString();
int n1 = Integer.parseInt(n1s);
int n2 = Integer.parseInt(n2s);
return Math.max(n1, n2) - Math.min(n1, n2);
}
}
Here is a Python implementation:
def kc_count(start_int):
def kc_calc(n):
ns1 = ''.join(sorted("%04d" % n))
ns2 = ns1[::-1]
return max(int(ns1), int(ns2)) - min(int(ns1), int(ns2))
ct = 0;
while True:
start_int = kc_calc(start_int)
ct += 1
if start_int == 6174:
break
return ct
assert(kc_count(3524) == 3)
assert(kc_count(3087) == 2)
assert(kc_count(8352) == 1)
assert(kc_count(6174) == 1)

Single character instance from string

i was wondering how can i create a method where i can get the single instance from a string and give it a numericValue for example, if theres a String a = "Hello what the hell" there are 4 l characters and i want to give a substring from the String a which is Hello and give it numeric values. Right now in my program it gets all the character instances from string so the substring hello would get number values from the substring hell too because it also has the same characters.
my code :
public class Puzzle {
private static char[] letters = {'a','b','c','d','e','f','g','h','i', 'j','k','l','m','n','o','p','q','r','s',
't','u','v','w','x','y','z'};
private static String input;
private static String delimiters = "\\s+|\\+|//+|=";
public static void main(String[]args)
{
input = "help + me = please";
System.out.println(putValues(input));
}
//method to put numeric values for substring from input
#SuppressWarnings("static-access")
public static long putValues(String input)
{
Integer count;
long answer = 0;
String first="";
String second = "";
StringBuffer sb = new StringBuffer(input);
int wordCounter = Countwords();
String[] words = countLetters();
System.out.println(input);
if(input.isEmpty())
{
System.out.println("Sisestage mingi s6na");
}
if(wordCounter == -1 ||countLetters().length < 1){
return -1;
}
for(Character s : input.toCharArray())
{
for(Character c : letters)
{
if(s.equals(c))
{
count = c.getNumericValue(c) - 9;
System.out.print(s.toUpperCase(s) +"="+ count + ", ");
}
}
if(words[0].contains(s.toString()))
{
count = s.getNumericValue(s);
//System.out.println(count);
first += count.toString();
}
if(words[3].contains(s.toString())){
count = s.getNumericValue(s);
second += count.toString();
}
}
try {
answer = Long.parseLong(first)+ Long.parseLong(second);
} catch(NumberFormatException ex)
{
System.out.println(ex);
}
System.out.println("\n" + first + " + " + second + " = " + answer);
return answer;
}
public static int Countwords()
{
String[] countWords = input.split(" ");
int counter = countWords.length - 2;
if(counter == 0) {
System.out.println("Sisend puudu!");
return -1;
}
if(counter > 1 && counter < 3) {
System.out.println("3 sõna peab olema");
return -1;
}
if(counter > 3) {
System.out.println("3 sõna max!");
return -1;
}
return counter;
}
//method which splits input String and returns it as an Array so i can put numeric values after in the
//putValue method
public static String[] countLetters()
{
int counter = 0;
String[] words = input.split(delimiters);
for(int i = 0; i < words.length;i++) {
counter = words[i].length();
if(words[i].length() > 18) {
System.out.println("One word can only be less than 18 chars");
}
}
return words;
}
Program has to solve the word puzzles where you have to guess which digit corresponds to which letter to make a given equality valid. Each letter must correspond to a different decimal digit, and leading zeros are not allowed in the numbers.
For example, the puzzle SEND+MORE=MONEY has exactly one solution: S=9, E=5, N=6, D=7, M=1, O=0, R=8, Y=2, giving 9567+1085=10652.
import java.util.ArrayList;
public class main {
private static String ChangeString;
private static String[] ArrayA;
private static String a;
private static int wordnumber;
private static String temp;
public static void main(String[] args) {
// TODO Auto-generated method stub
a = "hello what the hell";
wordnumber = 0;
identifyint(a,wordnumber);
}
public static void identifyint (String a, int WhichWord){
ChangeString = a.split(" ")[WhichWord];
ArrayA = a.split(" ");
replaceword();
ArrayA[wordnumber] = ChangeString;
//System.out.print(ArrayA[wordnumber]);
a = "";
for(int i = 0; i<ArrayA.length;i++){
if(i==wordnumber){
a = a.concat(temp+ " ");
}
else{
a = a.concat(ArrayA[i]+" ");
}
}
System.out.print(a);
}
public static void replaceword(){
temp = "";
Character arr[] = new Character[ChangeString.length()];
for(int i = 0; i<ChangeString.length();i++){
arr[i] = ChangeString.charAt(i);
Integer k = arr[i].getNumericValue(arr[i])-9;
temp = temp.concat(""+k);
}
a = temp;
}
}
Change wordnumber to the word you want to replace each time. If this is not what you have asked for, please explain your question in more detail.

Char Arrays comparison

I am trying to build something like a hangman (for beginners)
I try this:
int i = 0;
int fails = 0;
boolean success = false;
boolean retval;
char[] defineword = new char[] { 'h', 'u', 'n', 'g' };
char[] givenchar = new char[0];
char[] testchar = new char[] { 'h' };
while (success == false && fails < 5) {
System.out.println("Give a char: ");
String word = input.next(); // INPUT STRING
givenchar = word.toCharArray(); // CONVERT
retval = Arrays.equals(givenchar, testchar);
System.out.println("THE LETTER IS " + retval);
if (retval == true) {
testchar[0] = defineword[i + 1];
} else {
fails++;
}
}
The problem is that it can't continue after the letter ('u'), it is stuck in 'u'.
One observation I will make is that you only real comparison is between givenchar, and testchar.
retval = Arrays.equals(givenchar, testchar);
It would make sense that this wouldn't work once you got past u because testchar never gets past u either. I think you might have intended to add an i++ somewhere.
testchar[0] = defineword[i + 1];
package mer;
import java.util.Scanner;
public class Aswe
{
int i=0;
int f=0;
boolean suc=false;
boolean ret;
char[] dw=new char[]{'h','u','n','g'};
char[] gc=new char[0];
char[] tc=new char[]{'h'};
Scanner i1;
public void me()
{
i1=new Scanner(System.in);
while(suc==false&&f<5)
{
System.out.println("give a char");
String ch=i1.nextLine();
gc=ch.toCharArray();
ret=eual(gc,tc);
System.out.println("the letter is"+ret);
if(ret)
{
tc[0]=dw[i+1];
}
else
f++;
}
}
public boolean eual(char[] a,char[] b)
{
if(a[0]==b[0])
return true;
else
return false;
}
public static void main(String ... args)
{
new Aswe().me();
}
}
private int fails = 0;
private final int maxFails = 5;
private char[] answer = new char[] {'j','a','v','a'};
public Hangman() {
Scanner scan = new Scanner(System.in);
/*
* Game Loop
*/
while(fails < maxFails){
System.out.print("Enter a char: ");
char givenChar = scan.next().charAt(0);
System.out.println("Given char is: " + Check(answer,givenChar));
}
}
/*
* Check if the char exists in the array.
*/
private boolean Check(char[] array,char value){
for(int i = 0; i < array.length; i++){
if(array[i] == value){
return true;
}
}
/*
* Okay did not find any char that match return false.
*/
return false;
}

generating list of small ascii strings

I want to create a generator class, in java, to produce the next smallest unique ascii string, where the resultant string must begin with an a-Z, and each subsequent letter can be a-Z or 0-9.
The strings are being used to minify variables in a javascript file.
Any suggestions on a tool out there which does this or some rough code as to how you'd implement?
If you need to use a different selection of characters you can use
public static void main(String... ignored) {
String prev = "";
for (int i = 0; i < 40000000; i++) {
String s = asId(i);
if (s.length() > prev.length())
System.out.print(prev + "\n" + s + " to ");
prev = s;
}
}
static char[] CHARS = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray();
public static String asId(long number) {
StringBuilder sb = new StringBuilder();
long div = number < 52 ? 1 : 52;
while (div <= number / 62) div *= 62;
while (div > 0) {
sb.append(CHARS[((int) (number / div % 62))]);
div /= 62;
}
return sb.toString();
}
prints
0 to Z
10 to ZZ
100 to ZZZ
1000 to
You can use the following in Java.
public static String asId(long number) {
return (char) ('a' + number % 26)
+ (number >= 26 ? Long.toString(number / 26, 36) : "");
}
If you concerned about negative numbers you can use.
public static String asId(long number) {
long lowBit = number & 1;
long highBits = number >>> 1;
return (char) ('a' + highBits % 13 + lowBit)
+ (number >= 26 ? Long.toString(highBits / 13, 36) : "");
}
Here are some ideas (not fully tested!!!)
import java.lang.*;
import java.util.*;
public class Test
{
static class VariablesIterator implements Iterator<String>
{
private List<Character> characters = new ArrayList<Character>();
private List<Integer> indices = new ArrayList<Integer>();
public VariablesIterator(String start)
{
char[] cs = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".toCharArray();
for (char c : cs)
{
characters.add(c);
}
for (int i = 0; i < start.length(); ++i)
{
indices.add(characters.indexOf(start.charAt(i)));
}
}
public boolean hasNext()
{
return true;
}
public String next()
{
String current = "";
for (int i = 0; i < indices.size(); ++i)
{
current += characters.get(indices.get(i));
}
Integer last = indices.get(indices.size() - 1);
if (indices.size() != 1 && last != 2*26 + 10 - 1 || indices.size() == 1 && last != 2*26 - 1)
{
indices.set(indices.size() - 1, last + 1);
}
else
{
indices.add(0);
}
return current;
}
public void remove()
{
throw new UnsupportedOperationException();
}
}
static class Variables implements Iterable<String>
{
public Iterator<String> iterator()
{
return new VariablesIterator("a");
}
}
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
for (String variable : new Variables())
{
System.out.println(variable);
in.nextLine();
}
}
}

Converting an int to a binary string representation in Java?

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.

Categories