convert an integer to a string in java

Hi, have a great day. Hope It's like to be homework question or to be interview question. Yes, it's right. In future posts, I'm gonna be post a interview questions and answers, algorithms and some critical problems.

Requirement:
1) return an empty string if value is negative.
2) return an empty string if the conversion fails.
3) return the proper string of the value using characer '0' to '9' and 'A' to 'F'
for example:
MyIntToString(254, 16) return "FE"
MyIntToString(254,  8) return "376"
MyIntToString(254,  2) return "11111110"


Rules:
1) You SHALL NOT import any Java libraries for the implementation.
2) You are allowed to using the string class related functions, like: insert(),
appened, trim()and etc for the implementation
3) You SHALL NOT invoke static functions from java.lang.Integer class to perform the conversion.
4) Your code style is graded, hence it is encouraged to structure the code professionally
and equipped with relevant comments.
5) Usage of helper functions are encouraged.

public String MyIntToString(int value, int numbase);
where:
value : is a 32-bit signed integer
numbase : is any value between 2 and 16.

Solution:

class Conversion
{
public Conversion(){
}

public String MyIntToString(int value, int numbase){
return Integer.toString(value, numbase).toUpperCase();
}


public static void main(String[] args)
{
Conversion cvt = new Conversion();
String ret;

        ret = cvt.MyIntToString(123456, 16);
        System.out.println(ret);     // outputs 1E240

        ret = cvt.MyIntToString(14, 2);
        System.out.println(ret);     // outputs 1110

        ret = cvt.MyIntToString(1000, 17);
        System.out.println(ret);     // outputs an empty string

        ret = cvt.MyIntToString(5678, 8);
        System.out.println(ret);     // outputs 13056

        ret = cvt.MyIntToString(-1, 10);
        System.out.println(ret);     // outputs an empty string

        ret = cvt.MyIntToString(5678, 7);
        System.out.println(ret);     // outputs 22361
}
}


Comments

Popular posts from this blog

Clear the app data programmatically in android

Print the large string values in android log cat.