You are given a list of n numbers from 1 to n-1, with one of the numbers repeated. Findout the repeated number?
Sum of all the distinct numbers from 1 to n-1 in the list will be n*(n-1)/2. Findout total sum of the given list. Now subtract n*(n-1)/2 from the list sum. Result will be the repeated number.
Write implementation of memcpy and memmove functions? What is the difference between the two?
Implementation of memcpy
void memcpy(void* dest, void* src, int n_size) {
char* d = (char*) dest;
char* s = (char*) src;
while(n_size– > 0) {
*d++ = *s++;
}
}
Implementation of memmove
void memmove(void* dest, void* src, int n_size) {
char* d = (char*) dest;
char* s = (char*) src;
if(d > s) {
while(n_size– > 0) {
*d– = *s–;
}
} else {
while(n_size– > 0) {
*d++ = *s++;
}
}
}
memmove ensure correct copying when the two buffers overlap.
Iterating over Map
A Map is an object that maps keys to values. A map cannot contain duplicate keys: Each key can map to at most one value. Map iteration can be done on the basis of key or value or key value set. Choose iteration according to your requirement.
productMap.put("P001", "Product 1");
productMap.put("P002", "Product 2");
productMap.put("P003", "Product 3");
productMap.put("P004", "Product 4");
productMap.put("P005", "Product 5");
System.out.println("--Iterating over Key Set(Method 1)---");
for(Object key : productMap.keySet()) {
System.out.println(key);
}
System.out.println("--Iterating over Key Set(Method 2)---");
Iterator keyIter = productMap.keySet().iterator();
while (keyIter.hasNext()) {
String element = (String)keyIter.next();
System.out.println(element);
}
System.out.println("--Iterating over Value Set--");
Iterator valueIter = productMap.values().iterator();
while(valueIter.hasNext()) {
System.out.println(valueIter.next());
}
System.out.println("--Iterating over Key Value Set--");
Iterator keyValIter = productMap.entrySet().iterator();
while(keyValIter.hasNext()) {
Map.Entry entry = (Map.Entry)keyValIter.next();
System.out.println(entry.getKey() + " => " + entry.getValue());
}
Chose iterator carefully for improved performance.