Related
So I'm currently working on a personal project and I made a program that tries to swap every 2 letter in a given string.
So I want the output like this:
(Note Input String is "abllte")
ballet
So I wrote this method
public static String codeString(String input) {
String firstLetter = "";
String secoundLetter = "";
String result = "";
for(int i = 0; i < input.length()-1; i++){
for(int c = 0; c < i; c = c +2)
{
firstLetter = input.substring(c,c + 1);
secoundLetter = input.substring(c + 1, c + 2);
}
result = result + secoundLetter + firstLetter;
}
return result;
}
But I get this output:
ababllll
Any idea how to solve this?
Thank you in advance!
You only need one loop. This works for both even and odd length character strings.
first, the methods used return the StringBuilder in its current modified state.
So sb.insert(i, sb.charAt(i+1)) inserts the char at i+1 at i
So if sb contained ab, StringBuilder would now contain bab
insert returns the modifed StringBuilder so now sb.deleteCharAt(i+2) deletes the second a (the one that was just copied).
this is then repeated until all characters are swapped.
Because of the constant inserting and deletion of characters this is not very efficient.
for (String s : new String[] { "abcdefg", "abcdefgh" }) {
StringBuilder sb = new StringBuilder(s);
for (int i = 0; i < sb.length() - 1; i += 2) {
sb.insert(i, sb.charAt(i + 1)).deleteCharAt(i + 2);
}
System.out.println(s + " -> " + sb);
}
Prints
abcdefg -> badcfeg
abcdefgh -> badcfehg
For a more efficient algorithm, this would be the way to go. It's also much more intuitive.
for (String s : new String[] { "abcdefg", "abcdefgh" }) {
char ch[] = s.toCharArray();
for (int i = 0; i < ch.length - 1; i+=2) {
char c = ch[i];
ch[i] = ch[i + 1];
ch[i + 1] = c;
}
String d = String.valueOf(ch);
System.out.println(s + " -> " + d);
}
This prints the same as above.
I'm not sure what the point of your nested for loop is. You can do this with just one loop.
public static String codeString(String input) {
String firstLetter = "";
String secoundLetter = "";
String result = "";
for(int i = 0; i < input.length()-1; i+=2){
firstLetter = input.substring(i,i+1);
secoundLetter = input.substring(i+1,i+2);
result = result + secoundLetter + firstLetter;
}
return result;
}
If your input string has an odd number of characters, you'll have to append the extra last character.
public static String codeString(String input) {
String firstLetter = "";
String secoundLetter = "";
String result = "";
for(int i = 0; i < input.length()-1; i+=2){
firstLetter = input.substring(i, i+1);
secoundLetter = input.substring(i+1, i+2);
result = result + secoundLetter + firstLetter;
}
if(input.length() % 2 == 1)
result += input.substring(input.length()-1, input.length());
return result;
}
You do not need a nested loop. Change the outer loop to step by 2 i.e. i = i + 2 and remove the inner loop.
public class Main {
public static void main(String[] args) {
System.out.println(codeString("abllte"));
}
public static String codeString(String input) {
String firstLetter = "";
String secondLetter = "";
String result = "";
for (int i = 0; i < input.length() - 1; i = i + 2) {
firstLetter = input.substring(i, i + 1);
secondLetter = input.substring(i + 1, i + 2);
result = result + secondLetter + firstLetter;
}
return result;
}
}
Output:
ballet
An alternative approach:
You can create a function with two parameters: input string as the first parameter and n as the second parameter, where every n characters in the input string need to be reversed.
public class Main {
public static void main(String[] args) {
System.out.println(codeString("abllte", 1));
System.out.println(codeString("abllte", 2));
System.out.println(codeString("abllte", 3));
System.out.println(codeString("abllte", 4));
}
public static String codeString(String input, int n) {
if (n <= input.length() / 2) {
StringBuilder result = new StringBuilder();
for (int i = 0; i < input.length() - n + 1; i = i + n) {
result.append(new StringBuilder(input.substring(i, i + n)).reverse());
}
return result.toString();
} else {
return input;
}
}
}
Output:
abllte
ballet
lbaetl
abllte
I'm trying to find the shortest palindrome that one can create from S by by adding 0 or more characters in front of it. For example the shortest palindrome can be constructed from 'baaa' is 'aaabaaa'. The two functions that I'm using are given below. This works for this case for doesn't yield the shortest result in all cases.
public static boolean checkPalindrome(String s){
for (int i = 0; i < s.length()/2; i++) {
if (s.charAt(i) != s.charAt(s.length() - i - 1)) return false;
}
return true;
}
public static int makePalindrome(String s){
int min = 0;
StringBuilder str = new StringBuilder(s);
for (int i = 1; i < s.length() ; i++) {
str.insert(0, s.charAt(i));
if (checkPalindrome(str.toString()) == true) {
min = str.length();
break;
}
}
return min;
}
I can't seem to figure out what logical step am I missing.
Your helper method checkPalindrome seems correct. Your thinking is also correct (append characters until the result is a palindrome), but the way you're going about it is wrong.
To reiterate: Our logic is, while our result is not a palindrome, take the next character from the end (moving towards the start of the string) and append it to the prefix. So for the string "abcd", we would try
"" + "abcd" -> "abcd" -> false
"d" + "abcd" -> "dabcd" -> false
"dc" + "abcd" -> "dcabcd" -> false
"dcb" + "abcd" -> "dcbabcd" -> true, terminate
Here's a fixed version:
public static String makePalindrome(String base){
String pref = "";
int i = base.length() - 1;
while(! checkPalindrome(pref + base)){
pref = pref + base.charAt(i);
i --;
}
return pref + base;
}
I am not sure i understand the question but from what i understood you want to turn Strings like Hello to olleHello To do this, loop trhough each char of the string with like:
String example = "Hello There Mate"; //our string
StringBuilder exampleBuilder = new StringBuilder();
for(int i=example.length()-1; i>0; i--)
exampleBuilder.append(example.charAt(i));
//Our loop, the reason why it is example.lenght-1
//is because we want the first letter to appear only
//1 time :)
String finalString = exampleBuilder.toString()+example;
//The final string, should be 'olleHello'
System.out.println(finalString);
Hope thats what you are looking for :D
IDEONE: http://ideone.com/tawjmG
We can find the shortest Palindrome using the following logic:
Find the midpoint, loop from 0 to midpoint, length-1 to midpoint.
If palindrome, return
If not palindrome, add 1 to midpoint, do same logic
In code:
static String shortestPalindrome(String s) {
if (s.length() == 1) return s;
return recShortestPalindrome(s, s.length()>>1, 0);
}
static String recShortestPalindrome(String s, int mid, int add) {
// AABBA[X]
int fakeLen = s.length() + add;
for (int i = 0; i < mid; i++) {
char c1 = s.charAt(i);
int p1 = fakeLen - 1 - i;
if (p1 < s.length()) {
char c2 = s.charAt(p1);
if (c2 != c1) {
return recShortestPalindrome(s, mid+1, add+1);
}
}
}
// found a pattern that works
String h1 = s.substring(0, mid);
String h2 = new StringBuilder(h1).reverse().toString();
String ret = h1+h2;
int midPoint = ret.length()/2;
if (ret.length()%2 == 0 && ret.length() >= 2) {
char c1 = ret.charAt(midPoint);
char c2 = ret.charAt(midPoint-1);
if (c1 == c2) {
return ret.substring(0, midPoint) + ret.substring(midPoint+1, ret.length());
}
}
return h1+h2;
}
Python Solution:
def isPalindrome(x):
if x == "":
return False
r = ""
r = str(x)
r = r[::-1]
return True if x == r else False
def makePalindrome(my_str):
pref = ""
i = len(my_str) - 1
while isPalindrome(pref + my_str) == False:
pref = pref + my_str[i]
i -= 1
return pref + my_str
my_str = "abcd"
print(makePalindrome(my_str))
i have this assignment for school which ask us to write code to find the longest common Substring. I have done that, but it only works with text that are not so big and it is being asked to find the common substring for Moby Dick and War And Peace. If you could point me in the right direction of what i'm doing wrong, i would appreciate it. The compiler is complaining that the error is in the substring method of the MyString class when i call it to create the SuffixArray but idk why its saying its too big, giving me the outofmemory
package datastructuresone;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Arrays;
import java.util.Scanner;
class SuffixArray
{
private final MyString[] suffixes;
private final int N;
public SuffixArray(String s)
{
N = s.length();
MyString snew = new MyString(s);
suffixes = new MyString[N];
for (int i = 0; i < N; i++)
{
suffixes[i] = snew.substring(i);
}
Arrays.sort(suffixes);
}
public int length()
{
return N;
}
public int index(int i)
{
return N - suffixes[i].length();
}
public MyString select(int i)
{
return suffixes[i];
}
// length of longest common prefix of s and t
private static int lcp(MyString s, MyString t)
{
int N = Math.min(s.length(), t.length());
for (int i = 0; i < N; i++)
{
if (s.charAt(i) != t.charAt(i))
{
return i;
}
}
return N;
}
// longest common prefix of suffixes(i) and suffixes(i-1)
public int lcp(int i)
{
return lcp(suffixes[i], suffixes[i - 1]);
}
// longest common prefix of suffixes(i) and suffixes(j)
public int lcp(int i, int j)
{
return lcp(suffixes[i], suffixes[j]);
}
}
public class DataStructuresOne
{
public static void main(String[] args) throws FileNotFoundException
{
Scanner in1 = new Scanner(new File("./build/classes/WarAndPeace.txt"));
Scanner in2 = new Scanner(new File("./build/classes/MobyDick.txt"));
StringBuilder sb = new StringBuilder();
StringBuilder sb1 = new StringBuilder();
while (in1.hasNextLine())
{
sb.append(in1.nextLine());
}
while (in2.hasNextLine())
{
sb1.append(in2.nextLine());
}
String text1 = sb.toString().replaceAll("\\s+", " ");
String text2 = sb1.toString().replaceAll("\\s+", " ");
int N1 = text1.length();
int N2 = text2.length();
SuffixArray sa = new SuffixArray(text1 + "#" + text2);
int N = sa.length();
String substring = "";
for (int i = 1; i < N; i++)
{
// adjacent suffixes both from second text string
if (sa.select(i).length() <= N2 && sa.select(i - 1).length() <= N2)
{
continue;
}
// adjacent suffixes both from first text string
if (sa.select(i).length() > N2 + 1 && sa.select(i - 1).length() > N2 + 1)
{
continue;
}
// check if adjacent suffixes longer common substring
int length = sa.lcp(i);
if (length > substring.length())
{
substring = sa.select(i).toString().substring(0, length);
System.out.println(substring + " ");
}
}
System.out.println("The length of the substring " + substring.length() + "length on first N " + N1 + " length of Second N " + N2
+ "The length of the array sa: " + N);
System.out.println("'" + substring + "'");
final class MyString implements Comparable<MyString>
{
public MyString(String str)
{
offset = 0;
len = str.length();
arr = str.toCharArray();
}
public int length()
{
return len;
}
public char charAt(int idx)
{
return arr[ idx + offset];
}
public int compareTo(MyString other)
{
int myEnd = offset + len;
int yourEnd = other.offset + other.len;
int i = offset, j = other.offset;
for (; i < myEnd && j < yourEnd; i++, j++)
{
if (arr[ i] != arr[ j])
{
return arr[ i] - arr[ j];
}
}
// reached end. Who got there first?
if (i == myEnd && j == yourEnd)
{
return 0; // identical strings
}
if (i == myEnd)
{
return -1;
} else
{
return +1;
}
}
public MyString substring(int beginIndex, int endIndex)
{
return new MyString(arr, beginIndex + offset, endIndex - beginIndex);
}
public MyString substring(int beginIndex)
{
return substring(beginIndex, offset + len);
}
public boolean equals(Object other)
{
return (other instanceof MyString) && compareTo((MyString) other) == 0;
}
public String toString()
{
return new String(arr, offset, len);
}
private MyString(char[] a, int of, int ln)
{
arr = a;
offset = of;
len = ln;
}
private char[] arr;
private int offset;
private int len;
}
Here:
for (int i = 0; i < N; i++)
{
suffixes[i] = snew.substring(i);
}
You are trying to store, not only the entire long string, but the entire string - 1 letter, and the entire string - 2 letters, etc. All of these are stored separately.
If your String were only 10 letters, you would be storing a total of 55 characters worth in 10 different string.
At 1000 characters, you are storing 500500 characters total.
More generally, you are having to handle, length*(length+1)/2 characters.
Just for fun, I don't know how many characters are in War and Peace, but with a page count around 1250, a typical words/page estimate being 250, and the average word being about 5 characters long, comes to:
(1250 * 250 * 5)*(1250 * 250 * 5 + 1)/2 = 1.2207039 * 10^12 characters.
The size of a char in memory being 2 bytes, so you're looking at about 2.22 TB in size (compared to 1.49 MB for just the text of the novel).
I count at least 3 copies of both texts in the first few lines of the code. Here's a few ideas
convert the spaces as you read each line in--not after they are huge strings. Don't forget the case of spaces at the front and end of lines.
build your MyString class using StringBuilder as the base instead of String. Do all the looking inside the StringBuilder with its native methods, if you can.
don't extract strings any more than you have to.
Look up the -Xmx java runtime option and set the heap space large than the default. You'll have to google this as I don't have it memorized. Just notice that -Xmx=1024M needs that M at the end. (Look at the file size to see how big the two books are.)
When you construct MyString, you call arr = str.toCharArray(); which makes a new copy of the string's character data. But in Java, a string is immutable - so why not store a reference to the string instead of a copy of its data?
You construct every suffix at once, but you only refer to one (well, two) at a time. If you recode your solution to only reference the suffixes it currently cares about, and construct them only when it needs them (and lose a reference to them afterwards), they can be garbage collected by Java. This will make running out of memory less likely. Compare the memory overhead of storing 2 strings to storing hundreds of thousands of strings :)
I wrote this program in Scala. Maybe you can translate it to Java.
class MyString private (private val string: String, startIndex: Int, endIndex: Int) extends Comparable[MyString] {
def this(string: String) = this(string, 0, string.length)
def length() = endIndex-startIndex
def charAt(i: Int) = {
if(i >= length) throw new IndexOutOfBoundsException
string.charAt(startIndex + i)
}
def substring(start: Int, end: Int): MyString = {
if(start < 0 || end > length || end < start) throw new IndexOutOfBoundsException
new MyString(string, startIndex + start, startIndex + end)
}
def substring(start: Int): MyString = substring(start, length)
def longestCommonSubstring(other: MyString): MyString = {
var index = 0
val len = math.min(length, other.length)
while(index < len && charAt(index) == other.charAt(index)) index += 1
substring(0, index)
}
def compareTo(other: MyString): Int = {
val len = math.min(length, other.length)
for(i <- 0 until len) {
if(charAt(i) > other.charAt(i)) return 1
if(charAt(i) < other.charAt(i)) return -1
}
length-other.length
}
def >(other: MyString) = compareTo(other) > 0
def <(other: MyString) = compareTo(other) < 0
override def equals(other: Any) = other.isInstanceOf[MyString] && compareTo(other.asInstanceOf[MyString]) == 0
override def toString() = "\"" + string.substring(startIndex, endIndex) + "\""
}
def readFile(name: String) = new MyString(io.Source.fromFile(name).getLines.mkString(" ").replaceAll("\\s+", " "))
def makeList(str: MyString) = (0 until str.length).map(i => str.substring(i)).toIndexedSeq
val string1 = readFile("WarAndPeace.txt")
val string2 = readFile("MobyDick.txt")
val (list1, list2) = (makeList(string1).sorted, makeList(string2).sorted)
var longestMatch = new MyString("")
var (index1, index2) = (0,0)
while(index1 < list1.size && index2 < list2.size) {
val lcs = list1(index1).longestCommonSubstring(list2(index2))
if(lcs.length > longestMatch.length) longestMatch = lcs
if(list1(index1) < list2(index2)) index1 += 1
else index2 += 1
}
println(longestMatch)
If I have a decimal number, how do I convert it to base 36 in Java?
Given a number i, use Integer.toString(i, 36).
See the documentation for Integer.toString
http://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#toString(int,%20int)
toString
public static String toString(int i, int radix)
....
The following ASCII characters are used as digits:
0123456789abcdefghijklmnopqrstuvwxyz
What is radix? You're in luck for Base 36 (and it makes sense)
http://docs.oracle.com/javase/7/docs/api/java/lang/Character.html#MAX_RADIX
public static final int MAX_RADIX 36
The following can work for any base, not just 36. Simply replace the String contents of code.
Encode:
int num = 586403532;
String code = "0123456789abcdefghijklmnopqrstuvwxyz";
String text = "";
int j = (int)Math.ceil(Math.log(num)/Math.log(code.length()));
for(int i = 0; i < j; i++){
//i goes to log base code.length() of num (using change of base formula)
text += code.charAt(num%code.length());
num /= code.length();
}
Decode:
String text = "0vn4p9";
String code = "0123456789abcdefghijklmnopqrstuvwxyz";
int num = 0;
int j = text.length();
for(int i = 0; i < j; i++){
num += code.indexOf(text.charAt(0))*Math.pow(code.length(), i);
text = text.substring(1);
}
First you have to convert your number it into the internal number format of Java (which happens to be 2-based, but this does not really matter here), for example by Integer.parseInt() (if your number is an integer less than 2^31). Then you can convert it from int to the desired output format. The method Integer.toString(i, 36) does this by using 0123456789abcdefghijklmnopqrstuvwxyz as digits (the decimal digits 0-9 and lower case english letters in alphabetic order). If you want some other digits, you can either convert the result by replacing the "digits" (for example toUpperCase), or do the conversion yourself - it is no magic, simply a loop of taking the remainder modulo 36 and dividing by 36 (with a lookup of the right digit).
If your number is longer than what int offers you may want to use long (with Long) or BigInteger instead, they have similar radix-converters.
If your number has "digits after the point", it is a bit more difficult, as most (finite) base-X-numbers are not exactly representable as (finite) base-Y-numbers if (a power of) Y is not a multiple of X.
This code works:
public class Convert {
public static void main(String[] args) {
int num= 2147483647;
String text="ABCD1";
System.out.println("num: " + num + "=>" + base10ToBase36(num));
System.out.println("text: " +text + "=>" + base36ToBase10(text));
}
private static String codeBase36 = "0123456789abcdefghijklmnopqrstuvwxyz";
//"0123456789 abcdefghij klmnopqrst uvwxyz"
//"0123456789 0123456789 0123456789 012345"
private static String max36=base10ToBase36(Integer.MAX_VALUE);
public static String base10ToBase36(int inNum) {
if(inNum<0) {
throw new NumberFormatException("Value "+inNum +" to small");
}
int num = inNum;
String text = "";
int j = (int)Math.ceil(Math.log(num)/Math.log(codeBase36.length()));
for(int i = 0; i < j; i++){
text = codeBase36.charAt(num%codeBase36.length())+text;
num /= codeBase36.length();
}
return text;
}
public static int base36ToBase10(String in) {
String text = in.toLowerCase();
if(text.compareToIgnoreCase(max36)>0) {
throw new NumberFormatException("Value "+text+" to big");
}
if(!text.replaceAll("(\\W)","").equalsIgnoreCase(text)){
throw new NumberFormatException("Value "+text+" false format");
}
int num=0;
int j = text.length();
for(int i = 0; i < j; i++){
num += codeBase36.indexOf(text.charAt(text.length()-1))*Math.pow(codeBase36.length(), i);
text = text.substring(0,text.length()-1);
}
return num;
}
}
If you dont want to use Integer.toString(Num , base) , for instance, in my case which I needed a 64 bit long variable, you can use the following code:
Using Lists in JAVA facilitates this conversion
long toBeConverted=10000; // example, Initialized by 10000
List<Character> charArray = new ArrayList<Character>();
List<Character> charArrayFinal = new ArrayList<Character>();
int length=10; //Length of the output string
long base = 36;
while(toBeConverted!=0)
{
long rem = toBeConverted%base;
long quotient = toBeConverted/base;
if(rem<10)
rem+=48;
else
rem+=55;
charArray.add((char)rem);
toBeConverted=quotient;
}
// make the array in the reverse order
for(int i=length-1;i>=0;--i){
if(i>=charArray.size()){
charArrayFinal.add((char) 48); // sends 0 to fix the length of the output List
} else {
charArrayFinal.add(charArray.get(i));
}
}
Example:
(278197)36=5YNP
Maybe I'm late to the party, but this is the solution I was using for getting Calc/Excel cell names by their index:
public static void main(final String[] args) {
final String base = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
System.out.println(toCustomBase(0, base));
System.out.println(toCustomBase(2, base));
System.out.println(toCustomBase(25, base));
System.out.println(toCustomBase(26, base));
System.out.println(toCustomBase(51, base));
System.out.println(toCustomBase(52, base));
System.out.println(toCustomBase(520, base));
}
public static String toCustomBase(final int num, final String base) {
final int baseSize = base.length();
if(num < baseSize) {
return String.valueOf(base.charAt(num));
}
else {
return toCustomBase(num / baseSize - 1, base) + base.charAt(num % baseSize);
}
}
Results:
A
C
Z
AA
AZ
BA
TA
Basically the solution accepts any custom radix. The idea was commandeered from here.
Not sure if the above answers did help but noting 'decimal' and 'to base36' I assume you want to convert a numeric value to base36. And as long as the Long value of the raw figure is within (0 - Long.MAX_VALUE):
String someNumericString = "9223372036854";
Long l = Long.valueOf(someNumericString);
String bases36 = Long.toString(l, 36);
System.out.println("base36 value: "+bases36);
output: 39p5pkj5i
Here is a method to convert base 10 to any given base.
public char[] base10Converter(int number, int finalBase) {
int quo;
int rem;
char[] res = new char[1];
do {
rem = number % finalBase;
quo = number / finalBase;
res = Arrays.copyOf(res, res.length + 1);
if (rem < 10) {
//Converting ints using ASCII values
rem += 48;
res[res.length - 1] = (char) rem;
} else {
//Convert int > 9 to A, B, C..
rem += 55;
res[res.length - 1] = (char) rem;
}
number /= finalBase;
} while (quo != 0);
//Reverse array
char[] temp = new char[res.length];
for (int i = res.length - 1, j = 0; i > 0; i--) {
temp[j++] = res[i];
}
return temp;
}
I got this code from this website in JavaScript, and this is my version in java:
public static String customBase (int N, String base) {
int radix = base.length();
String returns = "";
int Q = (int) Math.floor(Math.abs(N));
int R = 0;
while (Q != 0) {
R = Q % radix;
returns = base.charAt(R) + returns;
Q /= radix;
}
if(N == 0) {
return String.valueOf(base.toCharArray()[0]);
}
return N < 0 ? "-" + returns : returns;
}
This supports negative numbers and custom bases.
Decimal Addon:
public static String customBase (double N, String base) {
String num = (String.valueOf(N));
String[] split = num.split("\\.");
if(split[0] == "" || split[1] == "") {
return "";
}
return customBase(Integer.parseInt(split[0]), base)+ "." + customBase(Integer.parseInt(split[1]), base);
}
This can be helpful to you.The operation being performed on the 4 digit alphanumeric String and decimal number below 1679615. You can Modify code accordingly.
char[] alpaNum = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray();
String currentSeries = "";
int num = 481261;
String result = "";
String baseConversionStr = "";
boolean flag = true;
do
{
baseConversionStr = Integer.toString(num % 36) + baseConversionStr;
String position = "";
if(flag)
{
flag = false;
position = baseConversionStr;
}
else
{
position = Integer.toString(num % 36);
}
result += alpaNum[new Integer(position)];
num = num/36;
}
while (num > 0);
StringBuffer number = new StringBuffer(result).reverse();
String finalString = "";
if(number.length()==1)
{
finalString = "000"+articleNo;
}
else if(number.length()==2)
{
finalString = "00"+articleNo;
}
else if(number.length()==3)
{
finalString = "0"+articleNo;
}
currentSeries = finalString;
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.