Friday, July 24, 2015
A number x supports a number (x+b) where b is the number of set bits in binary representation of x, like if x = 3 then x supports (3+2)=5 as 3 has 2 1’s in its binary representation. Now you are provided with an array of numbers you have to print the supported number corresponding to each of the given number.
Thursday, July 2, 2015
Program to form a HashMap out of given String
For example:
Input : name=ashish&age=24&company=kyubatau&city=pune
output : a HashMap containing LHS values as Keys and RHS values as Values
//Program to form a HashMap out of given String
//O(n)
//Program to form a HashMap out of given String
//O(n)
import java.util.*;
public class StringMap{
static public void main(String args[]){
System.out.println(new StringMap().getStringMap("name=ashish&age=24&company=kyubatau&city=pune"));
}
public HashMap<String,String> getStringMap(String str){
String flag = "key";
String myKey = "", myVal = "";
HashMap<String,String> pairs = new HashMap<>();
for(int i=0 ; i<str.length() ; i++)
{
String curr = String.valueOf(str.charAt(i));
if(curr.equals("=" ))
{
flag = "value";
continue;
}
if(curr.equals("&"))
{
pairs.put(myKey,myVal);
flag = "key";
myKey = "";
myVal = "";
continue;
}
if(flag.equals("key"))
myKey = myKey + str.charAt(i);
else
if(flag.equals("value"))
myVal = myVal + str.charAt(i);
}
pairs.put(myKey,myVal);
return pairs;
}
}
output:
{city=pune, name=ashish, company=kyubatau, age=24}
Input : name=ashish&age=24&company=kyubatau&city=pune
output : a HashMap containing LHS values as Keys and RHS values as Values
//Program to form a HashMap out of given String
//O(n)
//Program to form a HashMap out of given String
//O(n)
import java.util.*;
public class StringMap{
static public void main(String args[]){
System.out.println(new StringMap().getStringMap("name=ashish&age=24&company=kyubatau&city=pune"));
}
public HashMap<String,String> getStringMap(String str){
String flag = "key";
String myKey = "", myVal = "";
HashMap<String,String> pairs = new HashMap<>();
for(int i=0 ; i<str.length() ; i++)
{
String curr = String.valueOf(str.charAt(i));
if(curr.equals("=" ))
{
flag = "value";
continue;
}
if(curr.equals("&"))
{
pairs.put(myKey,myVal);
flag = "key";
myKey = "";
myVal = "";
continue;
}
if(flag.equals("key"))
myKey = myKey + str.charAt(i);
else
if(flag.equals("value"))
myVal = myVal + str.charAt(i);
}
pairs.put(myKey,myVal);
return pairs;
}
}
output:
{city=pune, name=ashish, company=kyubatau, age=24}
Subscribe to:
Comments (Atom)