Issue
Question:
Given a string, take the first 2 chars and return the string with the 2 chars added at both the front and back, so "kitten" yields"kikittenki". If the string length is less than 2, use whatever chars are there.
front22("kitten") → "kikittenki"
front22("Ha") → "HaHaHa"
front22("abc") → "ababcab"
My answer:
public String front22(String str) {
if(str.length() > 2) {
char first = str.charAt(0);
char second = str.charAt(1);
return first + second + str + first + second;
}
return str + str + str;
}
Results:
Expected Run results
front22("kitten") → "kikittenki" "212kittenki" X
front22("Ha") → "HaHaHa" "HaHaHa" OK
front22("abc") → "ababcab" "195abcab" X
front22("ab") → "ababab" "ababab" OK
front22("a") → "aaa" "aaa" OK
front22("") → "" "" OK
front22("Logic") → "LoLogicLo" "187LogicLo" X
So where are the numbers i.e. 212, 195 and 187 that are in front of my output are coming from? I am new to JAVA. Sorry if this is something very simple or basic that I don't know.I know I could have done it the following way, but just want to know what's going on with my first answer.
public String front22(String str) {
if(str.length() > 2){
return str.substring(0,2) + str + str.substring(0,2);
}
return str + str + str;
}
Solution
That's the ascii sum of the characters:
For your first case, i
has ascii 105
and k
has ascii 107
so their sum is 212
.
Try str.subString(0, 2)
instead of adding the char
variables.
Answered By - Ra1nWarden
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.