In below code string is passed in a method with numbers separated by space, now we need to provide sum of smallest two numbers in the string.
public class SumNearZero { public static int SumNearZero(String s) { String temp=s; int t1=0; for (int i = 0; i <s.length(); i++) { if(temp.contains(" ")) { t1++; temp=temp.substring(temp.indexOf(" ")+1); } } int a[]=new int[++t1]; int index=0; for(int i=0; i<s.length(); i++) { if(s.contains(" ")) { a[index]=Integer.parseInt(s.substring(0,s.indexOf(" "))); s=s.substring(s.indexOf(" ")+1); index++; } } a[index]=Integer.parseInt(s); for (int i = 0; i < a.length; i++) { for(int j=0; j<a.length-1; j++) { int c=a[j],n=a[j+1]; if(c>n) { int t=c; a[j]=n; a[j+1]=t; } } } int result=a.length>1 ? a[0]+a[1]:a[0]; return result; } public static void main(String[] args) { System.out.println(SumNearZero("35 96 10 20 5")); } } Above code is working fine but i want to reduce the code. if you provide some suggestion regarding this, I'll be happy to learn from you.
Restrictions : use of Collections, predefined methods e.g(String.split(),Arrays.sort()...)