I want to generate every possible binary sequence of numbers, where each sequence in the list is limited to a specific number of 1's and there is padding of zeros to make every list the same length.
For example, if the sequence is supposed to be 4 numbers long, and have 2 ones, all sequences would be:
1100 1010 1001 0110 0101 0011
and the zeros at the front of the number are preserved.
This can be solved using recursive function calls:
public class BinarySequences {
public static void main(String[] args) {
final int numCount = 4;
final int oneCount = 2;
checkSubString(numCount, oneCount, "");
for (String res : results) {
System.out.println(res);
}
}
private static List<String> results = new ArrayList<>();
private static void checkSubString(int numCount, int oneCount, String prefix) {
if ((numCount >= oneCount) && (oneCount >= 0)) {
if (numCount==1) {
if (oneCount==1) {
results.add(prefix + "1");
} else {
results.add(prefix + "0");
}
} else {
checkSubString(numCount-1, oneCount , prefix + "0");
checkSubString(numCount-1, oneCount-1, prefix + "1");
}
}
}
}
If you want to preserve the 0s, then just add padding:
int end = 100; //Change this
for (int i = 0; i <= end; i++) {
String bytestring = Integer.toBinaryString(i);
String padding = "00000000000000000000000000000000";
bytestring = padding.substring(0, 32 - bytestring.length()) + bytestring;
System.out.println(bytestring);
}
Try this:
//Edit your min and max, e.g. Integer.MAX_VALUE and Integer.MIN_VALUE
int min = 0;
int max = 10;
for(int i = min; i < max; i++){
//Make 16 bit long binary Strings
String s = String.format("%16s", Integer.toBinaryString(i)).replace(' ', '0');
//Make 4 bits long chunks
List<String> chunks = new ArrayList<>();
Matcher matcher = Pattern.compile(".{0,4}").matcher(s);
while (matcher.find()) {
chunks.add(s.substring(matcher.start(), matcher.end()));
}
StringBuilder b = new StringBuilder();
for (String c : chunks) {
//Here you can count the 1 and 0 of the current chunk with c.charAt(index)
b.append(c);
b.append(" ");
}
System.out.println(b.toString());
}
Requires org.apache.commons.lang.StringUtils, but this makes it a short one:
final int digits = 4;
final int onesrequired = 2;
int maxindex = (int) Math.pow(2, digits);
for (int i = 0; i < maxindex; i++) {
String binaryStr = Integer.toBinaryString(i);
if (StringUtils.countMatches(binaryStr, "1") == onesrequired) {
System.out.print(String.format("%" + digits + "s", binaryStr).replace(' ', '0') + " ");
}
}
Related
So far I need to round a number that I inputted and get it to 3 decimal places without those methods.
if(number !=(int)number){
number*=1000;
number=(int)number;
number=(double)number;
number/=1000;
System.out.println("-"+ number);
}
if(number ==(int)number){
System.out.println("-"+ number + "00");
}
With that above, it will work for any input except the ones with 2 decimal places, like 12.34 .
How do I make it work if i type 12.34 and displays 12.340?
Try something like this (truncates number):
number *= 1000.0;
if (((int) number) % 100 == 0) {
System.out.println((number / 1000.0) + "00");
} else if (((int) number) % 10 == 0) {
System.out.println((number / 1000.0) + "0");
} else {
System.out.println(number / 1000.0);
}
What about this? Works for the given inputs
public static String truncate(Double a, int digits) {
String[] values = a.toString().split("\\.");
String integer = values[0];
String decimal = values[1];
if (decimal.length() < digits) {
int n = digits - decimal.length();
for (int i = 0; i < n; i++) {
decimal += "0";
}
return integer + "." + decimal;
}
return integer + "." + decimal.substring(0, digits);
}
public static void main(String[] args) {
System.out.println(truncate(1.0, 7));
System.out.println(truncate(1.23719273, 4));
System.out.println(truncate(1d, 1));
}
Out
1.0000000
1.2371
1.0
you can use printf method like this:
System.out.printf("result = %.3f",number);
EDIT ( without using printf format specifiers)
void floatTruncate(float val){
float a = val;
String result = a + "";
int index = result.indexOf(".");
int zeroes = result.length() - 1 - index;
zeroes = 3 - zeroes;
for (int i = 1; i <= zeroes && zeroes < 3; i++) {
result = result + "0";
}
System.out.println("new result = " + result);
}
EDIT 2: ( if you want to keep only 3 decimal places if your input is is like number = 22.34567f and you want output as 22.345 then use this one
void floatTruncate(float val) {
float a = val;
String result = a + "";
int index = result.indexOf(".");
int zeroes = result.length() - 1 - index;
//use this logic if ur logic is to keep only 3 decimal places
if(zeroes>3){
result = result.substring(0, index+4);
}
zeroes = 3 - zeroes;
for (int i = 1; i <= zeroes && zeroes < 3; i++) {
result = result + "0";
}
System.out.println("new result = " + result);
}
sample outputs
a = 22.3f -> 22.300
a = 22.34f -> 22.340
a = 22.345f -> 22.345
a = 22.34567f -> 22.345
I have space separated string containing numbers in between like:
"abc123 ws32wd3 y3tg43 5tga89 a1a"
I have to parse the string to get the numbers from each token and then sum up all the digits extracted from tokens. I have written below code, but what I think is, if there is huge string, then there might be performance issue.
So, my questions are:
How can we improve the performance in below code?
Do we have another way to write the below code to solve the problem?
Code:
public class TestSum {
public static int doSum(String str){
String[] sArray = str.split(" ");
char[] chr = null;
String temp;
String number = "";
int sum=0;
for(String s : sArray){
chr = s.toCharArray();
for(char c : chr){
temp = String.valueOf(c);
if(isNum(temp)){
number = number + temp;
}
}
sum = sum + Integer.parseInt(number);
number="";
}
return sum;
}
public static boolean isNum(String nStr){
try{
Integer.parseInt(nStr);
return true;
}catch(NumberFormatException nfe){
return false;
}
}
public static void main(String[] args) {
System.out.println("Sum is "+ TestSum.doSum("abc123 ws32wd3 y3tg43 5tga89 a1a"));
}
}
This is the fastest I could think of:
public static int getSum(String str)
{
int sum = 0;
int exp = 1;
for (int i = str.length() - 1; i >= 0; i--)
{
final char c = str.charAt(i);
if (c >= '0' && c <= '9')
{
sum += (c - '0') * exp;
exp *= 10;
}
else
{
exp = 1;
}
}
return sum;
}
It iterates through string from right to left. Thanks to that, when it "sees" a digit it can add appropriate value, depending on the decimal position "seen" in the number.
Benchmark using Caliper
Results are different than in davecom's benchmark:
AUTHOR RUNTIME (NS) HOW MANY TIMES FASTER THAN JUNS
-----------------------------------------------------------
Adam 66.221 600
Old 579.873 70
Prabhakaran 20,012.750 2 (2x faster than Juns)
Juns 39,681.074 1
You can start improving the speed of the code by eliminating your isNum() method and using the built in Character.isDigit() method.
You may be able to further improve the speed by using a regular expression to extract the numbers out of each token instead of doing it with the loops.
Best of luck.
EDIT
Comparing the performance of some of the answers here, it would seem that #Prabhakaran's answer is slower than the original, while #OldCurmudgeon's is faster, and #Adam Stelmaszczyk's is the fastest :
import java.util.*;
public class TestSum {
public static int doSum(String str){
String[] sArray = str.split(" ");
char[] chr = null;
String temp;
String number = "";
int sum=0;
for(String s : sArray){
chr = s.toCharArray();
for(char c : chr){
temp = String.valueOf(c);
if(isNum(temp)){
number = number + temp;
}
}
sum = sum + Integer.parseInt(number);
number="";
}
return sum;
}
public static boolean isNum(String nStr){
try{
Integer.parseInt(nStr);
return true;
}catch(NumberFormatException nfe){
return false;
}
}
public static void testSum1(){
String str = "abc123 ws32wd3 y3tg43 5tga89 a1a";
str = str.replaceAll("[^0-9]+", " ");
List<String> asList = Arrays.asList(str.trim().split(" "));
int sum=0;
for (String string : asList) {
sum+=Integer.parseInt(string);
}
System.out.println(sum);
}
public static int doSum2(String str) {
int sum = 0;
// -1 means not started.
int start = -1;
for ( int i = 0; i < str.length(); i++ ) {
char ch = str.charAt(i);
if ( Character.isDigit(ch)) {
if ( start == -1 ) {
// Start of a number.
start = i;
}
} else {
if ( start != -1 ) {
// End of a number.
sum += Integer.parseInt(str.substring(start, i));
start = -1;
}
}
}
if ( start != -1 ) {
// A number at the end of the string.
sum += Integer.parseInt(str.substring(start, str.length()));
}
return sum;
}
public static int getSum(String str) {
int sum = 0;
int exp = 1;
for (int i = str.length() - 1; i >= 0; i--) {
final char c = str.charAt(i);
if (c >= '0' && c <= '9'){
sum += (c - '0') * exp;
exp *= 10;
}
else{
exp = 1;
}
}
return sum;
}
public static void main(String[] args) {
long startTime = System.nanoTime();
TestSum.testSum1();
long endTime = System.nanoTime();
System.out.println("testSum1 took " + (endTime - startTime) + " nanoseconds");
startTime = System.nanoTime();
System.out.println(TestSum.doSum("abc123 ws32wd3 y3tg43 5tga89 a1a"));
endTime = System.nanoTime();
System.out.println("doSum took " + (endTime - startTime) + " nanoseconds");
startTime = System.nanoTime();
System.out.println(TestSum.doSum2("abc123 ws32wd3 y3tg43 5tga89 a1a"));
endTime = System.nanoTime();
System.out.println("doSum2 took " + (endTime - startTime) + " nanoseconds");
startTime = System.nanoTime();
System.out.println(TestSum.getSum("abc123 ws32wd3 y3tg43 5tga89 a1a"));
endTime = System.nanoTime();
System.out.println("getSum took " + (endTime - startTime) + " nanoseconds");
}
}
Here is the output
Davids-MacBook-Air:desktop dave$ javac TestSum.java
Davids-MacBook-Air:desktop dave$ java TestSum
299
testSum1 took 1790000 nanoseconds
1379
doSum took 373000 nanoseconds
299
doSum2 took 173000 nanoseconds
299
getSum took 45000 nanoseconds
For maximum performance you could try something like this:
public static int doSum(String str) {
int sum = 0;
// -1 means not started.
int start = -1;
for ( int i = 0; i < str.length(); i++ ) {
char ch = str.charAt(i);
if ( Character.isDigit(ch)) {
if ( start == -1 ) {
// Start of a number.
start = i;
}
} else {
if ( start != -1 ) {
// End of a number.
sum += Integer.parseInt(str.substring(start, i));
start = -1;
}
}
}
if ( start != -1 ) {
// A number at the end of the string.
sum += Integer.parseInt(str.substring(start, str.length()));
}
return sum;
}
prints 299 which my calculator confirms is 123+32+3+3+43+5+89+1
String str = "abc123 ws32wd3 y3tg43 5tga89 a1a";
str = str.replaceAll("[^0-9]+", " ");
List<String> asList = Arrays.asList(str.trim().split(" "));
int sum=0;
for (String string : asList) {
sum+=Integer.parseInt(string);
}
System.out.println(asList);
System.out.println(sum);
Output
str = [123, 32, 3, 3, 43, 5, 89, 1]
sum = 299
Easier solution would be parse that string with regex \d finding digits, and then go through the new string (which contains only digits) and sum up every sign (digit) in that string.
You won't even have to check if you are summing up digits, because regex will do it for you.
I think in order to speed up your conversion you can use the following trick:
int representation of number = character representation of number - '0'
So int 5 = char 5 - '0'
or in other words
int 5 = '5' - '0'
This is because of how the ASCII table is indexed.
Some (untested) code I wrote super fast to illustrate:
for(int i=0; i<str.length(); i++){
if (!(str.charAt(i).isDigit()) continue;
do {
//now handle digit parsing into a number
crtNumber= crtNumber*10 + str.charAt(i)-'0'
i++
} while(str.charAt(i).isDigit());
queue.push(crtNumber);//save the number somewhere
crtNumber= 0; //prepare for next round
}
I wrote the following Java code, to find the intersection between the prefix and the suffix of a String in Java.
// you can also use imports, for example:
// import java.math.*;
import java.util.*;
class Solution {
public int max_prefix_suffix(String S) {
if (S.length() == 0) {
return 1;
}
// prefix candidates
Vector<String> prefix = new Vector<String>();
// suffix candidates
Vector<String> suffix = new Vector<String>();
// will tell me the difference
Set<String> set = new HashSet<String>();
int size = S.length();
for (int i = 0; i < size; i++) {
String candidate = getPrefix(S, i);
// System.out.println( candidate );
prefix.add(candidate);
}
for (int i = size; i >= 0; i--) {
String candidate = getSuffix(S, i);
// System.out.println( candidate );
suffix.add(candidate);
}
int p = prefix.size();
int s = suffix.size();
for (int i = 0; i < p; i++) {
set.add(prefix.get(i));
}
for (int i = 0; i < s; i++) {
set.add(suffix.get(i));
}
System.out.println("set: " + set.size());
System.out.println("P: " + p + " S: " + s);
int max = (p + s) - set.size();
return max;
}
// codility
// y t i l i d o c
public String getSuffix(String S, int index) {
String suffix = "";
int size = S.length();
for (int i = size - 1; i >= index; i--) {
suffix += S.charAt(i);
}
return suffix;
}
public String getPrefix(String S, int index) {
String prefix = "";
for (int i = 0; i <= index; i++) {
prefix += S.charAt(i);
}
return prefix;
}
public static void main(String[] args) {
Solution sol = new Solution();
String t1 = "";
String t2 = "abbabba";
String t3 = "codility";
System.out.println(sol.max_prefix_suffix(t1));
System.out.println(sol.max_prefix_suffix(t2));
System.out.println(sol.max_prefix_suffix(t3));
System.exit(0);
}
}
Some test cases are:
String t1 = "";
String t2 = "abbabba";
String t3 = "codility";
and the expected values are:
1, 4, 0
My idea was to produce the prefix candidates and push them into a vector, then find the suffix candidates and push them into a vector, finally push both vectors into a Set and then calculate the difference. However, I'm getting 1, 7, and 0. Could someone please help me figure it out what I'm doing wrong?
I'd write your method as follows:
public int max_prefix_suffix(String s) {
final int len = s.length();
if (len == 0) {
return 1; // there's some dispute about this in the comments to your post
}
int count = 0;
for (int i = 1; i <= len; ++i) {
final String prefix = s.substring(0, i);
final String suffix = s.substring(len - i, len);
if (prefix.equals(suffix)) {
++count;
}
}
return count;
}
If you need to compare the prefix to the reverse of the suffix, I'd do it like this:
final String suffix = new StringBuilder(s.substring(len - i, len))
.reverse().toString();
I see that the code by #ted Hop is good..
The question specify to return the max number of matching characters in Suffix and Prefix of a given String, which is a proper subset. Hence the entire string is not taken into consideration for this max number.
Ex. "abbabba", prefix and suffix can have abba(first 4 char) - abba (last 4 char),, hence the length 4
codility,, prefix(c, co,cod,codi,co...),, sufix (y, ty, ity, lity....), none of them are same.
hence length here is 0.
By modifying the count here from
if (prefix.equals(suffix)) {
++count;
}
with
if (prefix.equals(suffix)) {
count = prefix.length();// or suffix.length()
}
we get the max length.
But could this be done in O(n).. The inbuilt function of string equals, i believe would take O(n), and hence overall complexity is made O(n2).....
i would use this code.
public static int max_prefix_suffix(String S)
{
if (S == null)
return -1;
Set<String> set = new HashSet<String>();
int len = S.length();
StringBuilder builder = new StringBuilder();
for (int i = 0; i < len - 1; i++)
{
builder.append(S.charAt(i));
set.add(builder.toString());
}
int max = 0;
for (int i = 1; i < len; i++)
{
String suffix = S.substring(i, len);
if (set.contains(suffix))
{
int suffLen = suffix.length();
if (suffLen > max)
max = suffLen;
}
}
return max;
}
#ravi.zombie
If you need the length in O(n) then you just need to change Ted's code as below:
int max =0;
for (int i = 1; i <= len-1; ++i) {
final String prefix = s.substring(0, i);
final String suffix = s.substring(len - i, len);
if (prefix.equals(suffix) && max < i) {
max =i;
}
return max;
}
I also left out the entire string comparison to get proper prefix and suffixes so this should return 4 and not 7 for an input string abbabba.
I'm having string consisting of a sequence of digits (e.g. "1234"). How to return the String as an int without using Java's library functions like Integer.parseInt?
public class StringToInteger {
public static void main(String [] args){
int i = myStringToInteger("123");
System.out.println("String decoded to number " + i);
}
public int myStringToInteger(String str){
/* ... */
}
}
And what is wrong with this?
int i = Integer.parseInt(str);
EDIT :
If you really need to do the conversion by hand, try this:
public static int myStringToInteger(String str) {
int answer = 0, factor = 1;
for (int i = str.length()-1; i >= 0; i--) {
answer += (str.charAt(i) - '0') * factor;
factor *= 10;
}
return answer;
}
The above will work fine for positive integers, if the number is negative you'll have to do a little checking first, but I'll leave that as an exercise for the reader.
If the standard libraries are disallowed, there are many approaches to solving this problem. One way to think about this is as a recursive function:
If n is less than 10, just convert it to the one-character string holding its digit. For example, 3 becomes "3".
If n is greater than 10, then use division and modulus to get the last digit of n and the number formed by excluding the last digit. Recursively get a string for the first digits, then append the appropriate character for the last digit. For example, if n is 137, you'd recursively compute "13" and tack on "7" to get "137".
You will need logic to special-case 0 and negative numbers, but otherwise this can be done fairly simply.
Since I suspect that this may be homework (and know for a fact that at some schools it is), I'll leave the actual conversion as an exercise to the reader. :-)
Hope this helps!
Use long instead of int in this case.
You need to check for overflows.
public static int StringtoNumber(String s) throws Exception{
if (s == null || s.length() == 0)
return 0;
while(s.charAt(0) == ' '){
s = s.substring(1);
}
boolean isNegative = s.charAt(0) == '-';
if (s.charAt(0) == '-' || (s.charAt(0) == '+')){
s = s.substring(1);
}
long result = 0l;
for (int i = 0; i < s.length(); i++){
int value = s.charAt(i) - '0';
if (value >= 0 && value <= 9){
if (!isNegative && 10 * result + value > Integer.MAX_VALUE ){
throw new Exception();
}else if (isNegative && -1 * 10 * result - value < Integer.MIN_VALUE){
throw new Exception();
}
result = 10 * result + value;
}else if (s.charAt(i) != ' '){
return (int)result;
}
}
return isNegative ? -1 * (int)result : (int)result;
}
Alternate approach to the answer already posted here. You can traverse the string from the front and build the number
public static void stringtoint(String s){
boolean isNegative=false;
int number =0;
if (s.charAt(0)=='-') {
isNegative=true;
}else{
number = number* 10 + s.charAt(0)-'0';
}
for (int i = 1; i < s.length(); i++) {
number = number*10 + s.charAt(i)-'0';
}
if(isNegative){
number = 0-number;
}
System.out.println(number);
}
Given the right hint, I think most people with a high school education can solve this own their own. Every one knows 134 = 100x1 + 10x3 + 1x4
The key part most people miss, is that if you do something like this in Java
System.out.println('0'*1);//48
it will pick the decimal representation of character 0 in ascii chart and multiply it by 1.
In ascii table character 0 has a decimal representation of 48. So the above line will print 48. So if you do something like '1'-'0' That is same as 49-48. Since in ascii chart, characters 0-9 are continuous, so you can take any char from 0 to 9 and subtract 0 to get its integer value. Once you have the integer value for a character, then converting the whole string to int is straight forward.
Here is another one solution to the problem
String a = "-12512";
char[] chars = a.toCharArray();
boolean isNegative = (chars[0] == '-');
if (isNegative) {
chars[0] = '0';
}
int multiplier = 1;
int total = 0;
for (int i = chars.length - 1; i >= 0; i--) {
total = total + ((chars[i] - '0') * multiplier);
multiplier = multiplier * 10;
}
if (isNegative) {
total = total * -1;
}
Use this:
static int parseInt(String str) {
char[] ch = str.trim().toCharArray();
int len = ch.length;
int value = 0;
for (int i=0, j=(len-1); i<len; i++,j--) {
int c = ch[i];
if (c < 48 || c > 57) {
throw new NumberFormatException("Not a number: "+str);
}
int n = c - 48;
n *= Math.pow(10, j);
value += n;
}
return value;
}
And by the way, you can handle the special case of negative integers, otherwise it will throw exception NumberFormatException.
You can do like this: from the string, create an array of characters for each element, keep the index saved, and multiply its ASCII value by the power of the actual reverse index. Sum the partial factors and you get it.
There is only a small cast to use Math.pow (since it returns a double), but you can avoid it by creating your own power function.
public static int StringToInt(String str){
int res = 0;
char [] chars = str.toCharArray();
System.out.println(str.length());
for (int i = str.length()-1, j=0; i>=0; i--, j++){
int temp = chars[j]-48;
int power = (int) Math.pow(10, i);
res += temp*power;
System.out.println(res);
}
return res;
}
Using Java 8 you can do the following:
public static int convert(String strNum)
{
int result =strNum.chars().reduce(0, (a, b)->10*a +b-'0');
}
Convert srtNum to char
for each char (represented as 'b') -> 'b' -'0' will give the relative number
sum all in a (initial value is 0)
(each time we perform an opertaion on a char do -> a=a*10
Make use of the fact that Java uses char and int in the same way. Basically, do char - '0' to get the int value of the char.
public class StringToInteger {
public static void main(String[] args) {
int i = myStringToInteger("123");
System.out.println("String decoded to number " + i);
}
public static int myStringToInteger(String str) {
int sum = 0;
char[] array = str.toCharArray();
int j = 0;
for(int i = str.length() - 1 ; i >= 0 ; i--){
sum += Math.pow(10, j)*(array[i]-'0');
j++;
}
return sum;
}
}
public int myStringToInteger(String str) throws NumberFormatException
{
int decimalRadix = 10; //10 is the radix of the decimal system
if (str == null) {
throw new NumberFormatException("null");
}
int finalResult = 0;
boolean isNegative = false;
int index = 0, strLength = str.length();
if (strLength > 0) {
if (str.charAt(0) == '-') {
isNegative = true;
index++;
}
while (index < strLength) {
if((Character.digit(str.charAt(index), decimalRadix)) != -1){
finalResult *= decimalRadix;
finalResult += (str.charAt(index) - '0');
} else throw new NumberFormatException("for input string " + str);
index++;
}
} else {
throw new NumberFormatException("Empty numeric string");
}
if(isNegative){
if(index > 1)
return -finalResult;
else
throw new NumberFormatException("Only got -");
}
return finalResult;
}
Outcome:
1) For the input "34567" the final result would be: 34567
2) For the input "-4567" the final result would be: -4567
3) For the input "-" the final result would be: java.lang.NumberFormatException: Only got -
4) For the input "12ab45" the final result would be: java.lang.NumberFormatException: for input string 12ab45
public static int convertToInt(String input){
char[] ch=input.toCharArray();
int result=0;
for(char c : ch){
result=(result*10)+((int)c-(int)'0');
}
return result;
}
Maybe this way will be a little bit faster:
public static int convertStringToInt(String num) {
int result = 0;
for (char c: num.toCharArray()) {
c -= 48;
if (c <= 9) {
result = (result << 3) + (result << 1) + c;
} else return -1;
}
return result;
}
This is the Complete program with all conditions positive, negative without using library
import java.util.Scanner;
public class StringToInt {
public static void main(String args[]) {
String inputString;
Scanner s = new Scanner(System.in);
inputString = s.nextLine();
if (!inputString.matches("([+-]?([0-9]*[.])?[0-9]+)")) {
System.out.println("error!!!");
} else {
Double result2 = getNumber(inputString);
System.out.println("result = " + result2);
}
}
public static Double getNumber(String number) {
Double result = 0.0;
Double beforeDecimal = 0.0;
Double afterDecimal = 0.0;
Double afterDecimalCount = 0.0;
int signBit = 1;
boolean flag = false;
int count = number.length();
if (number.charAt(0) == '-') {
signBit = -1;
flag = true;
} else if (number.charAt(0) == '+') {
flag = true;
}
for (int i = 0; i < count; i++) {
if (flag && i == 0) {
continue;
}
if (afterDecimalCount == 0.0) {
if (number.charAt(i) - '.' == 0) {
afterDecimalCount++;
} else {
beforeDecimal = beforeDecimal * 10 + (number.charAt(i) - '0');
}
} else {
afterDecimal = afterDecimal * 10 + number.charAt(i) - ('0');
afterDecimalCount = afterDecimalCount * 10;
}
}
if (afterDecimalCount != 0.0) {
afterDecimal = afterDecimal / afterDecimalCount;
result = beforeDecimal + afterDecimal;
} else {
result = beforeDecimal;
}
return result * signBit;
}
}
Works for Positive and Negative String Using TDD
//Solution
public int convert(String string) {
int number = 0;
boolean isNegative = false;
int i = 0;
if (string.charAt(0) == '-') {
isNegative = true;
i++;
}
for (int j = i; j < string.length(); j++) {
int value = string.charAt(j) - '0';
number *= 10;
number += value;
}
if (isNegative) {
number = -number;
}
return number;
}
//Testcases
public class StringtoIntTest {
private StringtoInt stringtoInt;
#Before
public void setUp() throws Exception {
stringtoInt = new StringtoInt();
}
#Test
public void testStringtoInt() {
int excepted = stringtoInt.convert("123456");
assertEquals(123456,excepted);
}
#Test
public void testStringtoIntWithNegative() {
int excepted = stringtoInt.convert("-123456");
assertEquals(-123456,excepted);
}
}
//Take one positive or negative number
String str="-90997865";
//Conver String into Character Array
char arr[]=str.toCharArray();
int no=0,asci=0,res=0;
for(int i=0;i<arr.length;i++)
{
//If First Character == negative then skip iteration and i++
if(arr[i]=='-' && i==0)
{
i++;
}
asci=(int)arr[i]; //Find Ascii value of each Character
no=asci-48; //Now Substract the Ascii value of 0 i.e 48 from asci
res=res*10+no; //Conversion for final number
}
//If first Character is negative then result also negative
if(arr[0]=='-')
{
res=-res;
}
System.out.println(res);
public class ConvertInteger {
public static int convertToInt(String numString){
int answer = 0, factor = 1;
for (int i = numString.length()-1; i >= 0; i--) {
answer += (numString.charAt(i) - '0') *factor;
factor *=10;
}
return answer;
}
public static void main(String[] args) {
System.out.println(convertToInt("789"));
}
}
I have a string, "abc". How would a program look like (if possible, in Java) who permute the String?
For example:
abc
ABC
Abc
aBc
abC
ABc
abC
AbC
Something like this should do the trick:
void printPermutations(String text) {
char[] chars = text.toCharArray();
for (int i = 0, n = (int) Math.pow(2, chars.length); i < n; i++) {
char[] permutation = new char[chars.length];
for (int j =0; j < chars.length; j++) {
permutation[j] = (isBitSet(i, j)) ? Character.toUpperCase(chars[j]) : chars[j];
}
System.out.println(permutation);
}
}
boolean isBitSet(int n, int offset) {
return (n >> offset & 1) != 0;
}
As you probably already know, the number of possible different combinations is 2^n, where n equals the length of the input string.
Since n could theoretically be fairly large, there's a chance that 2^n will exceed the capacity of a primitive type such as an int. (The user may have to wait a few years for all of the combinations to finish printing, but that's their business.)
Instead, let's use a bit vector to hold all of the possible combinations. We'll set the number of bits equal to n and initialize them all to 1. For example, if the input string is "abcdefghij", the initial bit vector values will be {1111111111}.
For every combination, we simply have to loop through all of the characters in the input string and set each one to uppercase if its corresponding bit is a 1, else set it to lowercase. We then decrement the bit vector and repeat.
For example, the process would look like this for an input of "abc":
Bits: Corresponding Combo:
111 ABC
110 ABc
101 AbC
100 Abc
011 aBC
010 aBc
001 abC
000 abc
By using a loop rather than a recursive function call, we also avoid the possibility of a stack overflow exception occurring on large input strings.
Here is the actual implementation:
import java.util.BitSet;
public void PrintCombinations(String input) {
char[] currentCombo = input.toCharArray();
// Create a bit vector the same length as the input, and set all of the bits to 1
BitSet bv = new BitSet(input.length());
bv.set(0, currentCombo.length);
// While the bit vector still has some bits set
while(!bv.isEmpty()) {
// Loop through the array of characters and set each one to uppercase or lowercase,
// depending on whether its corresponding bit is set
for(int i = 0; i < currentCombo.length; ++i) {
if(bv.get(i)) // If the bit is set
currentCombo[i] = Character.toUpperCase(currentCombo[i]);
else
currentCombo[i] = Character.toLowerCase(currentCombo[i]);
}
// Print the current combination
System.out.println(currentCombo);
// Decrement the bit vector
DecrementBitVector(bv, currentCombo.length);
}
// Now the bit vector contains all zeroes, which corresponds to all of the letters being lowercase.
// Simply print the input as lowercase for the final combination
System.out.println(input.toLowerCase());
}
public void DecrementBitVector(BitSet bv, int numberOfBits) {
int currentBit = numberOfBits - 1;
while(currentBit >= 0) {
bv.flip(currentBit);
// If the bit became a 0 when we flipped it, then we're done.
// Otherwise we have to continue flipping bits
if(!bv.get(currentBit))
break;
currentBit--;
}
}
String str = "Abc";
str = str.toLowerCase();
int numOfCombos = 1 << str.length();
for (int i = 0; i < numOfCombos; i++) {
char[] combinations = str.toCharArray();
for (int j = 0; j < str.length(); j++) {
if (((i >> j) & 1) == 1 ) {
combinations[j] = Character.toUpperCase(str.charAt(j));
}
}
System.out.println(new String(combinations));
}
You can also use backtracking to solve this problem:
public List<String> letterCasePermutation(String S) {
List<String> result = new ArrayList<>();
backtrack(0 , S, "", result);
return result;
}
private void backtrack(int start, String s, String temp, List<String> result) {
if(start >= s.length()) {
result.add(temp);
return;
}
char c = s.charAt(start);
if(!Character.isAlphabetic(c)) {
backtrack(start + 1, s, temp + c, result);
return;
}
if(Character.isUpperCase(c)) {
backtrack(start + 1, s, temp + c, result);
c = Character.toLowerCase(c);
backtrack(start + 1, s, temp + c, result);
}
else {
backtrack(start + 1, s, temp + c, result);
c = Character.toUpperCase(c);
backtrack(start + 1, s, temp + c, result);
}
}
Please find here the code snippet for the above :
public class StringPerm {
public static void main(String[] args) {
String str = "abc";
String[] f = permute(str);
for (int x = 0; x < f.length; x++) {
System.out.println(f[x]);
}
}
public static String[] permute(String str) {
String low = str.toLowerCase();
String up = str.toUpperCase();
char[] l = low.toCharArray();
char u[] = up.toCharArray();
String[] f = new String[10];
f[0] = low;
f[1] = up;
int k = 2;
char[] temp = new char[low.length()];
for (int i = 0; i < l.length; i++)
{
temp[i] = l[i];
for (int j = 0; j < u.length; j++)
{
if (i != j) {
temp[j] = u[j];
}
}
f[k] = new String(temp);
k++;
}
for (int i = 0; i < u.length; i++)
{
temp[i] = u[i];
for (int j = 0; j < l.length; j++)
{
if (i != j) {
temp[j] = l[j];
}
}
f[k] = new String(temp);
k++;
}
return f;
}
}
You can do something like
```
import java.util.*;
public class MyClass {
public static void main(String args[]) {
String n=(args[0]);
HashSet<String>rs = new HashSet();
helper(rs,n,0,n.length()-1);
System.out.println(rs);
}
public static void helper(HashSet<String>rs,String res , int l, int n)
{
if(l>n)
return;
for(int i=l;i<=n;i++)
{
res=swap(res,i);
rs.add(res);
helper(rs,res,l+1,n);
res=swap(res,i);
}
}
public static String swap(String st,int i)
{
char c = st.charAt(i);
char ch[]=st.toCharArray();
if(Character.isUpperCase(c))
{
c=Character.toLowerCase(c);
}
else if(Character.isLowerCase(c))
{
c=Character.toUpperCase(c);
}
ch[i]=c;
return new String(ch);
}
}
```