Epic Systems Interview Question
Software Engineer / DevelopersCountry: United States
Interview Type: Written Test
Hi hengxingtianxia,
the code for DecimaltoOctal is wrong. instead of returning sb.toString(), you should return sb.reverse().toString().
#include <iostream>
#include <sstream>
#include <algorithm>
using namespace std;
int getOctal(int n){
int oct=0;
int mul=1;
while(n>0){
oct+=(n%8)*mul;
mul*=10;
n/=8;
}
return oct;
}
bool isPal(int n){
stringstream ss;
ss<<n;
string str;
ss>>str;
string revStr = str;
reverse(revStr.begin(),revStr.end());
if(str==revStr) return true;
return false;
}
int main(){
int lo=1;
int hi=100000;
for(int i=lo;i<=hi;i++){
int octal = getOctal(i);
if(isPal(i)&&isPal(octal)){
cout<<i<<" "<<octal<<endl;
}
}
return 0;
}
package epic;
public class DecToOct {
public static void main(String args[]){
System.out.println("Palindrome");
Integer limit = 1000;
int i;
for(i=1; i<limit; i++)
convertDecToOct(i);
}
public static void convertDecToOct(Integer dec){
Integer oct = 0;
Integer tmp = 0;
String revoct="-1";
Integer org =dec;
while(dec>0){
tmp = dec%8;
dec = (dec-tmp)/8;
if(revoct.equals("-1")){
revoct = String.valueOf(tmp);
}
else{
revoct = String.valueOf(tmp) + revoct ;
}
}
StringBuffer rev = new StringBuffer();
rev.append(revoct);
if(Integer.parseInt(rev.toString()) == org){
System.out.println(org + " " +revoct);
System.out.println("palindrome");
}
}
}
* Negative numbers are not palindrome.
* The range is limited to integer range [0, INT_MAX].
bool checkPalindrome(int num, int base) {
string ret;
if (num == 0) return true;
while (num) {
ret.push_back(num % base + '0');
num /= base;
}
int low(0), high(ret.size() - 1);
while (low < high)
if (ret[low++] != ret[high--]) return false;
return true;
}
void twoTypePalindrome(pair<int, int> range) {
if (range.first > range.second || range.first < 0) return;
for (int num = range.first; num <= range.second; ++num) {
if (checkPalindrome(num, 10) && checkPalindrome(num, 8))
cout << num << ' ';
}
}
public class PalindromewithOcta {
public static void main(String[] args) {
// TODO Auto-generated method stub
int minrange = 0;
int maxrange = 100;
for(int i=minrange;i<maxrange;i++)
{
checkForPalindrome(i);
}
}
public static boolean ifPalindrome(String s)
{
int j = s.length()-1;
for(int i=0; i< s.length()/2;i++)
{
if(s.charAt(i)!=s.charAt(j))
return false;
j--;
}
return true;
}
public static void checkForPalindrome(int num)
{
String decimalequivalent = Integer.toString(num);
boolean dec = ifPalindrome(decimalequivalent);
String hexequivalent = Integer.toOctalString(num);
boolean hex = ifPalindrome(hexequivalent);
if(dec && hex)
System.out.println(num);
}
}
Compiled! considered from 0 to a given range.
- hengxingtianxia October 18, 2014