Write your own Integer to String (itoa) converter.
Implement your own Integer to ASCII (itoa) method which converts an Integer to String.
Input 1: 123Output: "123" (as String)
Input 2: 0Output: "0" (as String)
Input 3: 8Output: "8" (as String)
Input 2: 0
Output: "0" (as String)
Input 3: 8
Output: "8" (as String)
Algorithm
Before we look into the algorithm, lets understand the ASCII ranges for 0-9.
ASCII Char
---------------
48 0
49 1
50 2
51 3
52 4
53 5
54 6
55 7
56 8
57 9
so if we have integer 4 and we want to get the char representation of 4, we can get by
char number = '0' + 4 which would be 48 + 4 = 52 and when we do ((char) 52) we get '4'.
similarly, if we have integer 7 and we want to get the char representation of 7, we can get by
char number = '0' + 7 which would be 48 + 7 = 55 and when we do ((char) 55) we get '7'.
Lets jump to original problem, if given the number 123
Mod and Divide the number by 10 to read each digits from end, once we have the digit convert it in the way shown below and put in StringBuilder.
Java Program to convert Integer To Ascii.
package javabypatel; public class IntegerToASCII { public static void main(String[] args) { System.out.println(integerToAscii(10)); } private static String integerToAscii(int num) { StringBuilder sb = new StringBuilder(); while (num > 0) { int lastDigit = num % 10; char ch = (char) ('0' + lastDigit); // since we are processing the last digit first(reverse order), // inserting at 0th position so that output is not in reverse order. sb.insert(0, ch); num /= 10; } return sb.toString(); } }
You may also like to see
Advanced Java Multithreading Interview Questions & Answers
Type Casting Interview Questions and Answers In Java?
Exception Handling Interview Question-Answer
Method Overloading - Method Hiding Interview Question-Answer
How is ambiguous overloaded method call resolved in java?
Method Overriding rules in Java
Interface interview questions and answers in Java
Enjoy !!!!
If you find any issue in post or face any error while implementing, Please comment.
Post a Comment