Unable to get the difference at the correct position

I am getting all the differences at the 1 index

@Vishu_1801,

https://ide.codingblocks.com/s/219542 I have corrected your code.

Add char to your stringbuilder and then add the difference. After the loop, just add the last char to your stringbuilder.

This approach is much better as compared to insertion because after you insert a char in your stringbuilder, the length changes and you need to keep a count of where you are inserting your next char.

1 Like

Sir Can we change the length of the stringbuilder if yes then how??

@Vishu_1801,
keep a variable j and do i+j instead of i+1. and increment j by 1 in every iteration.

Sorry sir i am unable to comprehend that

for what are we taking this variable i+j I mean what will be the purpose of this

@Vishu_1801,

		int d = (int)s.charAt(i+1) - (int)s.charAt(i);
		sb.insert( i+1, d);

let’s say that sb is acb.
here i=0, d = 2, now d will be inserted at i+1 or at index = 1; hence sb becomes a2cb
now i++;
here i=1,d= -1, now d will be again inserted at i+1 or at index = 2; but sb now is a2-1cb

Now if we keep a variable j. We count the number of insertions with j.

here i=0, j=1, d = 2, now d will be inserted at i+j or at index = 1; hence sb becomes a2cb
now i++; and j++;
here i=1, j=2, d= -1, now d will be again inserted at i+j or at index = 3; and sb is a2c-1b

1 Like

Thankyou sir i got that

@Vishu_1801,

Please mark the doubt as resolved and if you have any more doubts please reply on this thread. Also, please rate your experience. :sweat_smile:

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.