Recreate valueOf(double d) in Java's String class - java

I made an object, MyString. I can't figure out how to recreate valueOf(double d). I recreated valueOf for integers. Just to make it easier I limited the amount of decimal places to 8. How can I recreate valueOf(double d)?
public class MyString {
private char[] a;
public MyString(String s) {
this.a = s.toCharArray();
}
public MyString(char[] a) {
this.a = a;
}
public String toString() {
return new String(a);
}
public int length() {
return a.length;
}
public char charAt(int i) {
return a[i];
}
public static MyString valueOf(int i) {
int digits = (int)(Math.log10(i)+1);
char[] b = new char[digits];
for (int j = 0; j < digits; j++) {
b[j] = (char) (48 + i / 10);
i = i % 10;
if (i < 10) {
b[j + 1] = (char)(48 + i);
break;
}
}
MyString ms = new MyString(b);
return ms;
}
public static MyString valueOf(double d) {
char[] d1 = new char[digits];
//Take each digit of the number and enter it into the array
MyString ms = new MyString(d1);
return ms;
}
public static void main(String[] args) {
}
}

I assume you are doing this for fun... so here is the approach I took. You have valueOf(int i) already, so why not basically reuse that function. Just take the double and keep multiplying it by 10 until you have an int. Keep track of where the decimal place goes, then you basically call your valueOf(int i) but also include the decimal point.
I had trouble running your code so I re-did valueOf(int i) then created valueOf(int i, int decimalSpot), passing in -1 or 0 for the decimal spot then it's an integer value and don't use a decimal place.
Anyway, here is what I came up with. It's late, so probably not the cleanest code, but should give you a proof of concept.
public class MyString {
private char[] a;
public MyString(String s) {
this.a = s.toCharArray();
}
public MyString(char[] a) {
this.a = a;
}
public String toString() {
return new String(a);
}
public int length() {
return a.length;
}
public char charAt(int i) {
return a[i];
}
public static MyString valueOf(int i) {
return MyString.valueOf(i,-1);
}
public static MyString valueOf(double d) {
int decimalPlace = 0;
while (d != (int)d)
{
decimalPlace++;
d = d*10;
}
return MyString.valueOf((int)d,decimalPlace);
}
public static MyString valueOf(int i, int decimalSpot) {
int index=0;
int digits = (int)(Math.log10(i)+1);
int stringLength=digits;
if (decimalSpot == 0) decimalSpot=-1; // Don't return 1234. - just return 1234
if (decimalSpot != -1)
{
// Include an extra spot for the decimal
stringLength++;
}
char[] b = new char[stringLength];
for (int j = digits-1; j >= 0; j--) {
int power = (int) Math.pow(10,j);
int singleDigit = (int) Math.floor(i/power);
i = i - power*singleDigit;
b[index++] = (char) (48 + singleDigit);
if (decimalSpot==j)
{
b[index++] = '.';
}
}
MyString ms = new MyString(b);
return ms;
}
public static void main(String[] args) {
MyString ms = MyString.valueOf(12345);
System.out.println(ms);
ms = MyString.valueOf(12345.12313);
System.out.println(ms);
}
}

Rather than trying to solve this problem for every possible source datatype you should be just concentrating on constructing your class from a String. Then all you have to do is delegate this method and all the others you haven't done yet to the corresponding String method in each case, take the resulting String, and construct your object with that String.

Related

Java: Number of vowel in a string

I was asked to write a class NumberOcc with these methods:
-method getNbOcc which takes as arguments a string str and a character 'c' and return the number of occurence of the character 'c'.
-method dspNbOcc which displays the value returned by getNbOcc
-method getNbVoy which returns the number of vowel inside a string str
-method dspNbVoy which displays the value returned by getNbVoy
The problem is the value returned by getNbVoy is wrong, example: for str=stackexchange it returns 34 vowels.
public class NumberOcc {
static int count1=0;
static int count2=0;
public static int getNbOcc(String str, char c) {
for(int i=0;i<str.length();i++) {
if (str.charAt(i)==c)
count1++;}
return count1;
}
public static void dspNbOcc() {
System.out.println(count1);
}
public static int getNbVoy(String str) {
String vowel="aeiouy";
for(int j=0;j<vowel.length();j++) {
count2+=getNbOcc(str,vowel.charAt(j));}
return count2;
}
public static void dspNbVoy() {
System.out.println(count2);
}
}
TestClass
public class TestNumberOcc {
public static void main(String[] args) {
String str="stackexchange";
NumberOcc.getNbOcc(str, 'e');
NumberOcc.dspNbOcc();
NumberOcc.getNbVoy(str);
NumberOcc.dspNbVoy();
}
}
Thanks for helping
Remove the static fields, pass the values to the methods. And use them to display the results. Like,
public static int getNbOcc(String str, char c) {
int count = 0;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == c) {
count++;
}
}
return count;
}
public static void dspNbOcc(String str, char c) {
System.out.println(getNbOcc(str, c));
}
public static int getNbVoy(String str) {
int count = 0;
char[] vowels = "aeiouy".toCharArray();
for (char ch : vowels) {
count += getNbOcc(str.toLowerCase(), ch);
}
return count;
}
public static void dspNbVoy(String str) {
System.out.println(getNbVoy(str));
}
And then testing everything is as simple as
public static void main(String[] args) {
String str = "stackexchange";
NumberOcc.dspNbOcc(str, 'e');
NumberOcc.dspNbVoy(str);
}
the issue is you're not initializing your count1 (nor count2, but that bug doesn't affect anything in this case) at the beginning of your count method... add this line to the beginning of your getNbOcc method before the loop:
public static int getNbOcc(String str, char c) {
count1 = 0; // add this line
for(int i=0;i<str.length();i++) {
The solution is to apply what you did in your countLetterInString function to countVowelsInString. Just remember to use local variables. You will run into issues with static/global variables if the function is called more than once, but local variables will work the same way every time.
public static int countVowelsInString(String str) {
String vowels = "aeiouy";
// Move counter into the function
int numVowels = 0;
for(int j = 0;j<vowel.length();j++) {
numVowels += getNbOcc(str, vowel.charAt(j));
}
return numVowels;
}

reversing an integer in java without a loop

This is an homework problem
Is there a way tor reverse a number in Java without using any loops? The only solution I can think of is reversing it using String and then casting it back to an integer.
If you want to reverse a number withour using any loop you can use Recursion method call. Following program is doing same
public static void reverseMethod(int number) {
if (number < 10) {
System.out.println(number);
return;
} else {
System.out.print(number % 10);
reverseMethod(number / 10);
}
}
public static void main(String args[]) {
int num = 4567;
reverseMethod(num);
}
Even if you were to reverse the number by casting it into a String, you would still need a loop if you want the program to work when having ints of different sizes. If I were to make a method to reverse a number but could not do it with loops, I would probably do it with recursion (which still uses loops indirectly). The code will look something like this:
class Main {
public static void main(String[] args) {
String input = "1234"; // or scanner to take in input can be implemented
System.out.println(Integer.parseInt(reverseInt(input)));
}
public static String reverseInt(String x) {
if (x.length() == 1) {
return x;
} else {
return x.substring(x.length() - 1) + reverseInt(x.substring(0, x.length() - 1));
}
}
}
Hope this helps!
By using reverse() of StringBuilder:
int number = 1234;
String str = String.valueOf(number);
StringBuilder builder = new StringBuilder(str);
builder.reverse();
number = Integer.parseInt(builder.toString());
System.out.println(number);
will print:
4321
if you want reverse method without loop and recursion then use this code
int a=12345;
int b,c,d,e,f;
b=a%10;
c=a%100/10;
d=a%1000/100;
e=a%10000/1000;
f=a%100000/10000;
System.out.println(b+","+c+","+d+","+e+","+f);
you can go like :
public int reverse(int x) {
String o = "";
if (x < 0) {
x *= -1;
String s = Integer.toString(x);
o += "-";
o += new StringBuilder(s).reverse().toString();
}
else {
String s = Integer.toString(x);
o += new StringBuilder(s).reverse().toString();
}
try {
int out = Integer.parseInt(o);
//System.out.println(s);
return out; }
catch (NumberFormatException e) {
return 0;
}
}
This is a solution using recursive method call
public class Tester{
public static int findReverse(int num, int temp){
if(num==0){
return temp;
}else if(num<10){
return temp*10 + num; //up to this is stopping condition
}else{
temp = temp*10 + num%10;
return findReverse(num/10, temp);
}
}
public static void main(String args[]){
int num = 120021;
int reverseNum = findReverse(num, 0);
System.out.println(reverseNum);
if(num == reverseNum)
System.out.println(num +" is a palindrome!");
else
System.out.println(num +" is not a palindrome!");
}
}
This will be fast.
static int reverseNum(int num) {
StringBuilder sb = new StringBuilder(String.valueOf(num));
sb.reverse();
return Integer.parseInt(sb.toString());
}

How to substring a String in java when it has Double bytes chracters

I have a string that might contain both Unicode and UTF-8 characters. This makes it difficult when I want to save them to a database that doesn't deal with Unicode characters. The database I am using is PostgreSQL. They might be to big for a certain column this is a simple example for my situation
public static void main(String[] args) {
String test= "İİİİİİİİİİ";
byte[] bytesOrig = null;
bytesOrig = test.getBytes("UTF-8");
System.out.println("bytesOrig="+new String(bytesOrig));
byte[] bytesFive = new byte[5];
System.arraycopy(bytesOrig, 0, bytesFive, 0, 5);
System.out.println("bytes-Five="+new String(bytesFive));
System.out.println("Substring="+test.substring(0,5));
System.out.println("Substring real length=" + test.substring(0,5).getBytes().length);
}
I cant use the String.substring method since it will NOT help me in case of double bytes characters - i have tried working with Bytes-Array copy but it means that the last characters might be deleted.
And this is the Debug info:
bytesOrig=İİİİİİİİİİ
bytes-Five=İİ�
Substring=İİİİİ
Substring real length=10
You can see since I have only part of the Bytes array - I don't want the last character to appear as �
You can try this: the changing places are shows in comment.
public static void main(String[] args) throws UnsupportedEncodingException {
String test= "İİİİİİİİİİ";
System.out.println("test.length() = " + test.length()); // out: 10
byte[] bytesOrig;
bytesOrig = test.getBytes("UTF-8"); // but after get bytes will return 20
System.out.println("bytesOrig.length = " + bytesOrig.length); // it
System.out.println("bytesOrig="+new String(bytesOrig));
byte[] bytesFive = new byte[10]; // 1. so change here to twice
System.arraycopy(bytesOrig, 0, bytesFive, 0, 10); // 2. change here also
System.out.println("bytes-Five="+new String(bytesFive));
System.out.println("Substring="+test.substring(0,5));
System.out.println("Substring real length=" + test.substring(0,5).getBytes().length);
}
And here is the output:
test.length() = 10
bytesOrig.length = 20
bytesOrig=İİİİİİİİİİ
bytes-Five=İİİİİ
Substring=İİİİİ
Substring real length=10
Most of the logic is done at transformOverhead method
according to the value, we will increase i.
public class ZoneTrimTransformer implements ZoneTransformer {
private int maxLength;
public ZoneTrimTransformer(int maxLength) {
this.maxLength = maxLength;
}
#Override
public Object transform(Object value) {
if (value == null) {
return null;
}
else {
String val = value.toString();
if (getDBRequireLength(val) > getJavaLength(val) ){
return transformOverhead(val);
}
else if (val != null && getJavaLength(val) > maxLength) {
// Trim
val = val.substring(0, maxLength);
}
return val;
}
}
public static void main(String[] args) {
System.out.println("1234567".substring(0, 5));
}
public int getJavaLength(String val) {
return val.length();
}
public int getDBRequireLength(String val) {
return val.getBytes().length;
}
private Object transformOverhead(Object s) {
byte[] byeArray = s.toString().getBytes();
if (byeArray.length < maxLength) maxLength = byeArray.length;
int n16 = 0;
int advance = 1;
int i = 0;
while (i < maxLength) {
advance = 1;
if ((byeArray[i] & 0x80) == 0) i += 1;
else if ((byeArray[i] & 0xE0) == 0xC0) i += 2;
else if ((byeArray[i] & 0xF0) == 0xE0) i += 3;
else { i += 4; advance = 2; }
if (i <= maxLength) n16 += advance;
}
return s.toString().substring(0,n16);
}
}
And a test class for it:
#Category(UnitTest.class)
#RunWith(MockitoJUnitRunner.class)
public class ZoneTrimTransformerTest {
#Test
public void testLengths()
{
ZoneTrimTransformer lztr = new ZoneTrimTransformer(5);
assertEquals(lztr.transform("İİİİİİİİİİ"),"İİ");
assertEquals(lztr.getDBRequireLength(lztr.transform("İİİİİİİİİİ").toString()),4);
assertEquals(lztr.getJavaLength(lztr.transform("İİİİİİİİİİ").toString()),2);
assertEquals(lztr.transform("%&*%$^&$$^&$").toString(),"%&*%$");
assertEquals(lztr.getDBRequireLength(("%&*%$^&$$^&$").toString()),12);
assertEquals(lztr.getJavaLength(("%&*%$^&$$^&$").toString()),12);
assertEquals(lztr.transform("媒体アカウント名"),"媒");
assertEquals(lztr.getDBRequireLength(("媒体アカウント名").toString()),24);
assertEquals(lztr.getJavaLength(("媒体アカウント名").toString()),8);
assertEquals(lztr.transform("媒体媒体アカウント名アカウント名"),"媒");
assertEquals(lztr.getDBRequireLength(("媒体媒体アカウント名アカウント名").toString()),48);
assertEquals(lztr.getJavaLength(("媒体媒体アカウント名アカウント名").toString()),16);
assertEquals(lztr.transform("SÄ°STA+UNÄ°VERSAL"),"SÄ°");
assertEquals(lztr.getDBRequireLength(("SÄ°STA+UNÄ°VERSAL").toString()),21);
assertEquals(lztr.getJavaLength(("SÄ°STA+UNÄ°VERSAL").toString()),17);
assertEquals(lztr.transform("1234567890"),"12345");
assertEquals(lztr.getDBRequireLength(("1234567890").toString()),10);
assertEquals(lztr.getJavaLength(("1234567890").toString()),10);
assertEquals(lztr.transform("abcdefghI"),"abcde");
assertEquals(lztr.getDBRequireLength(("abcdefghI").toString()),9);
assertEquals(lztr.getJavaLength(("abcdefghI").toString()),9);
assertEquals(lztr.transform("אהגדהוזחט"),"אה");
assertEquals(lztr.getDBRequireLength(("אהגדהוזחט").toString()),18);
assertEquals(lztr.getJavaLength(("אהגדהוזחט").toString()),9);
assertEquals(lztr.transform("ABAA"),"ABAA");
assertEquals(lztr.getDBRequireLength(("ABAA").toString()),4);
assertEquals(lztr.getJavaLength(("ABAA").toString()),4);
assertEquals(lztr.getDBRequireLength(lztr.transform("ABCE").toString()),4);
assertEquals(lztr.getJavaLength(lztr.transform("ABCE").toString()),4);
}
}

How to design a test interface that times only some part of the code?

I want to time how long my code takes to perform on average over many test runs. In each test run, doWork() performs the work that I want to time. But I also want to checkWork() in each test run without it counting towards the time. I'm going to have many similar Exercise# classes, so I'd like to abstract the testing via a TestInterface. Is my current way a reasonable approach? Or is there a better design pattern / standard approach? Thanks in advance.
#FunctionalInterface
public interface TestInterface {
void test(final int NUM_TESTS);
}
public class TimeTests {
public static void test(TestInterface ti, final int NUM_TESTS, String testName) {
DecimalFormat df = new DecimalFormat("#.####");
long start = System.nanoTime();
ti.test(NUM_TESTS);
System.out.println("DEBUG: " + testName + " took "
+ df.format((System.nanoTime() - start) * 1.0 / NUM_TESTS)
+ " nanoseconds on average for " + NUM_TESTS + " tests");
}
}
public class Exercise1 {
private static final int NUM_TESTS = (int) Math.pow(10, 6);
private static void mainWork(List<Integer> A) {
// do stuff and time it
}
private static void checkWork(List<Integer> A) {
// do stuff but don't count it towards the time
}
public static void main(String[] args) {
TimeTests.test((NUM_TESTS_LOCAL) -> {
for (int i = 0; i < NUM_TESTS_LOCAL; ++i) {
List<Integer> A = new ArrayList<>();
// add random elements to A
mainWork(A);
checkWork(A);
}
}, NUM_TESTS, "Exercise1");
}
}
Okay, I think I managed to put together a decent framework (is this the right word?) for this task. If anybody could chime in to let me know if my approach is any good, I'd really appreciate it.
While my code seems to work fine for my use cases so far, I have a few questions:
In the interface definition of public interface CloneableTestInput<T extends CloneableTestInput<T>>, how is the type template <T extends CloneableTestInput<T> not a circular definition? I'm not sure I fully understand what that type template is saying.
Is there a way to make a generic CloneableList class that implements CloneableTestInput<List>? Currently, I need to make a separate implementation for each Collection type (e.g. ArrayList, LinkedList, ...). Similarly, is it possible to make a generic CloneableSet class that implements CloneableTestInput<Set>?
Thanks in advance :)
Testing Framework
Part I - An interface for test inputs
This allows TimeTests.java to work for generic input types.
public interface CloneableTestInput<T extends CloneableTestInput<T>> extends Cloneable {
T clone();
}
public class CloneableString implements CloneableTestInput<CloneableString> {
public String data;
public CloneableString() {}
public CloneableString(String input) { data = input; }
public CloneableString clone() { return new CloneableString(String.valueOf(data)); }
}
public class CloneableArrayList extends ArrayList implements CloneableTestInput<CloneableArrayList> {
public CloneableArrayList(ArrayList input) {
this.addAll(input);
}
#Override
public CloneableArrayList clone() {
return new CloneableArrayList(this);
}
}
Part II - An interface for timing tests
#FunctionalInterface
public interface TimeTestsInterface<outputType> {
void test(Callable<CloneableTestInput> formInput
, Function<CloneableTestInput, outputType> runAlgorithm
, Function<CloneableTestInput, outputType> getKnownOutput
, BiFunction<outputType, outputType, Boolean> checkResults
, final int NUM_TESTS, String testName);
}
public class TimeTests<outputType> implements TimeTestsInterface<outputType> {
public void test(Callable<CloneableTestInput> formInput
, Function<CloneableTestInput, outputType> runAlgorithm
, Function<CloneableTestInput, outputType> getKnownOutput
, BiFunction<outputType, outputType, Boolean> checkResults
, final int NUM_TESTS, String testName) {
try {
DecimalFormat df = new DecimalFormat("#.####");
long total = 0, start;
for (int i=0; i < NUM_TESTS; ++i) {
CloneableTestInput input = formInput.call();
CloneableTestInput orig_input = input.clone();
start = System.nanoTime();
outputType algorithmResult = runAlgorithm.apply(input);
total += System.nanoTime() - start;
outputType expectedResult = getKnownOutput.apply(orig_input);
assert(checkResults.apply(algorithmResult, expectedResult));
}
System.out.println("DEBUG: " + testName + " took "
+ df.format(total * 1.0 / NUM_TESTS)
+ " nanoseconds on average for " + NUM_TESTS + " tests");
} catch (Exception|AssertionError e) {
System.out.println(e.toString() + " - " + e.getMessage() + " - ");
e.printStackTrace();
}
}
}
Example Usages
Increment a BigInteger (uses CloneableArrayList)
/**
* Problem 6.2 from EPI
* Given an array A of digits encodiing a decimal number D,
* with MSD at A[0]. Update A to hold D + 1.
*/
public class PlusOne {
private static final int NUM_TESTS = (int) Math.pow(10, 5);
private static final int ARR_LENGTH = (int) Math.pow(10, 2);
private static ArrayList<Integer> plusOne(ArrayList<Integer> A) {
int n = A.size() - 1;
A.set(n, A.get(n) + 1);
for (int i = n; i > 0 && A.get(i) == 10; --i) {
A.set(i, 0);
A.set(i-1, A.get(i-1) + 1);
}
if (A.get(0) == 10) {
// Need additional digit up front as MSD
A.set(0,0);
A.add(0,1);
}
return A;
}
private static ArrayList<Integer> randArray(int len) {
ArrayList<Integer> A = new ArrayList<>();
if (len == 0) return A;
Random rgen = new Random();
A.add(rgen.nextInt(9) + 1);
--len;
while (len != 0) {
A.add(rgen.nextInt(10));
--len;
}
return A;
}
public static void main(String[] args) {
Callable<CloneableTestInput> formInput = () -> new CloneableArrayList(randArray(ARR_LENGTH));
Function<CloneableTestInput, ArrayList<Integer>> runAlgorithm =
(input) -> plusOne((ArrayList<Integer>) input);
Function<CloneableTestInput, ArrayList<Integer>> getKnownOutput =
(orig_input) -> {
BigInteger B = new BigInteger(Joiner.on("").join((ArrayList<Integer>) orig_input));
B = B.add(BigInteger.valueOf(1));
ArrayList<Integer> expectedOutput = new ArrayList<>();
while (B.compareTo(BigInteger.valueOf(0)) > 0) {
expectedOutput.add(0, B.mod(BigInteger.valueOf(10)).intValue());
B = B.divide(BigInteger.valueOf(10));
}
return expectedOutput;
};
BiFunction<ArrayList<Integer>, ArrayList<Integer>, Boolean> checkResults = List::equals;
TimeTests<ArrayList<Integer>> algTimer = new TimeTests<>();
algTimer.test(formInput, runAlgorithm, getKnownOutput, checkResults, NUM_TESTS, "PlusOne");
}
}
Can String be rearranged as a palindrome? (uses CloneableString)
public class CanStringBePalindrome {
private static final int INPUT_STRING_LENGTH = (int) Math.pow(10, 2);
private static final int NUM_TESTS = (int) Math.pow(10, 6);
private static boolean canFormPalindromeHash(final String s) {
Map<Character, Integer> charFreqs = new HashMap<>();
for (int i = 0; i < s.length(); ++i) {
char c = s.charAt(i);
if (!charFreqs.containsKey(c))
charFreqs.put(c, 1);
else
charFreqs.put(c, charFreqs.get(c) + 1);
}
int oddFreqCount = 0;
for (Map.Entry<Character, Integer> entry : charFreqs.entrySet()) {
if ((entry.getValue() % 2) != 0 && (++oddFreqCount > 1))
return false;
}
return true;
}
private static boolean canFormPalindromeSorting(final String s) {
// TODO : find faster/simpler way of getting frequency counts
char[] a = s.toCharArray();
Arrays.sort(a);
int oddFreqCount = 0;
int numCurrChar =1;
for (int i = 1; i < a.length && oddFreqCount <= 1; ++i) {
if(a[i] != a[i-1]) {
if ((numCurrChar & 1) != 0)
++oddFreqCount;
numCurrChar = 1;
} else
++numCurrChar;
}
if ((numCurrChar & 1) != 0)
++oddFreqCount;
return oddFreqCount <= 1;
}
private static String randString(int len) {
StringBuilder sb = new StringBuilder();
Random rgen = new Random();
while (len-- > 0)
sb.append((char)(rgen.nextInt(26) + 'A'));
return sb.toString();
}
public static void main(String[] args) {
Callable<CloneableTestInput> formInput = () -> new CloneableString(randString(INPUT_STRING_LENGTH));
Function<CloneableTestInput, Boolean > runAlgorithm =
(input) -> canFormPalindromeHash(((CloneableString)input).data);
Function<CloneableTestInput, Boolean> getKnownOutput =
(orig_input) -> canFormPalindromeSorting(((CloneableString)orig_input).data);
BiFunction<Boolean, Boolean, Boolean> checkResults = Boolean::equals;
TimeTests<Boolean> algTimer = new TimeTests<>();
algTimer.test(formInput, runAlgorithm, getKnownOutput, checkResults
, NUM_TESTS, "CanStringBePalindrome");
}
}

How would I decompress a String recursively WITHOUT any for loops?

For my assignment, I have to be able to decompress a string recursively with no for loops. I'm having some trouble trying to limit myself from using for loops and I'd appreciate it if I could receive some assistance. Towards the end, I have a for loop and I was wondering if there was a way I could remove it with something else and still have my program do what I intend for it to do
public class StringRec {
public static void main(String[] args) {
System.out.println("What text do you want to decompress?");
String compressedText = IO.readString();
System.out.println(decompress(compressedText));
}
public static String decompress(String compressedText) {
if (compressedText.length()<=1){
return compressedText;
}
String first="";
String rest="";
char c = compressedText.charAt(0);
if (Character.isLetter(c) == true) {
first = compressedText.substring(0,1);
rest = compressedText.substring(1);
return first + decompress(rest);
} else {
first = compressedText.substring(1,2);
rest = compressedText.substring(2);
int x = compressedText.charAt(0)-'0';
char y = compressedText.charAt(1);
String tst = "";
for(int i = 0; i < x; i++) {
tst = tst+y;
}
return tst + decompress(rest);
}
}
}
Use a while loop to do the same thing.
int i = 0;
while(i < x) {
i++;
tst += y;
}
If you can't use loops altogether, then use recursion.
int i = 0;
public String recursiveAppend(String tst) {
if(i >= x) {
i = 0;
return tst;
}
else return recursiveAppend(tst + y);
}
If you're using > Java 1.5, then use String tst = new String(new char[x]).replace('\0', y);. (from here)
Recursion to the rescue, bonus point if it is tail recursive:
String tst = repeat(y, x, "");
...
private String repeat(y, x, b) {
if (x == 0) {
return b;
}
return repeat(y, x - 1, b + y) ;
}

Categories

Resources