Write a program to convert an integer to the string.
Algorithm Explanation
![]() | Send number to the utility function. Create new string builder and iterate the number. |
![]() | Append to the string builder with n/10. The remaining iterated through the loop till the last number. |
![]() | Finally, return the string and display. |
Source Code
package com.dsacode.DataStructre.array; public class IntToString { public String intToString(int n) { if (n == 0) return "0"; StringBuilder sb = new StringBuilder(); while (n > 0) { int curr = n % 10; n = n/10; sb.append(curr); } String s = sb.substring(0); sb = new StringBuilder(); for (int i = s.length() -1; i >= 0; i--) { sb.append(s.charAt(i)); } return sb.substring(0); } public static void main(String[] args) { IntToString i = new IntToString(); System.out.println("Convert from Integer 123 to string : '" + i.intToString(123) +"'"); } }
Output
Convert from Integer 123 to string: '123'