Strings-Difference in Ascii Codes [codingblocks]

Take as input S, a string. Write a program that inserts between each pair of characters the difference between their ascii codes and print the ans.

Input Format
String

Constraints
Length of String should be between 2 to 1000.

Output Format
String

Sample Input
acb

 
Sample Output
a2c-1b

 
Explanation
For the sample case, the Ascii code of a=97 and c=99 ,the difference between c and a is 2.Similarly ,the Ascii code of b=98 and c=99 and their difference is -1. So the ans is a2c-1b.


Java Code:

 
 
/*
Amit Kumar
14-12-2020
IDE Code: https://ide.geeksforgeeks.org/8QRMw1GBdz
*/

package String;
import java.util.Scanner;

public class Strings_DifferenceInAsciiCodes {
    public static Scanner scanner = new Scanner(System.in);
    public static void main(String[] args) {
        String str = scanner.next();
        System.out.println(stringDifferenceInAsciiCodes(str));
    }

    private static String stringDifferenceInAsciiCodes(String str) {
        StringBuilder ansString = new StringBuilder();
        int i;
        for (i=0; i<str.length()-1; i++) {
            int diffrence = str.charAt(i+1) - str.charAt(i);
            ansString.append(str.charAt(i)).append(diffrence);
        }
        ansString.append(str.charAt(i));
        return ansString.toString();
    }
}

Comments

Post a Comment

Popular posts from this blog

Count ways to N'th Stair(Order does not matter)

Replace all ‘0’ with ‘5’ in an input Integer

Chocolate Distribution Problem

Remove characters from the first string which are present in the second string

Primality Test ( CodeChef Problem code: PRB01 )