c++ Getting wrong calculation from a function - c++

This is my code of a function. In main i check if temperature is in kelvin or fahrenheit. When I get temp_enota = 'F' from main ( I do because I checked with debugging), and temp = 116 for some reason function returns 0 when it should be around 46. Any ideas why? It works fine for kelvins.
float pretvorbaTemp(char temp_enota, float temp) {
if (temp_enota == 'K') {
temp = temp - 273.15;
}
else if (temp_enota == 'F') {
temp = (temp - 32) * (5 / 9);
}
return temp;
}
calling from main function
if (temp >= 283 && temp <= 323) {
temp_enota = 'K';
zacasna = 1;
cout << "Vnesena temperatura je v K, kar je enako "<<pretvorbaTemp(temp_enota, temp)<<" C" << endl;
}
else if (temp <= 122 && temp >= 50) {
temp_enota = 'F';
zacasna = 1;
cout << "Vnesena temperatura je v F, kar je enako "<<pretvorbaTemp(temp_enota, temp)<<" C" << endl;
}
else if (temp >= -10 && temp < 50) {
temp_enota = 'C';
zacasna = 1;
cout << "Vnesena temperatura je v C" << endl;
}
else {
zacasna = 0;
zacasna2 = 1;
}

The reason you get 0 is because the expression
5/9
will evaluate to 0 as these are two integer values, thus the compiler generates the code to do an integer division.
Just change to
5./9
to force floating point.

Do this:
float pretvorbaTemp(char temp_enota, float temp) {
if (temp_enota == 'K') {
temp = temp - 273.15;
}
else if (temp_enota == 'F') {
temp = (temp - 32.0) * (5.0 / 9.0);
}
return temp;
}
Here temp = (temp - 32) * (5 / 9); the values are int. You need to use them as float.

Related

DiceSum - How to extend if/ if-else statement to reroll dice if dice sum is not a certain number

#include <iostream>
#include <ctime>
#include <cstdlib>
#include <iomanip>
using namespace std;
int main()
{
int n;
int win = 0;
int lose = 0;
int dice1;
int dice2;
int diceSum;
srand(time(0));
cout << "How many turns would you like? ";
cin >> n;
for (int i = 1; i <= n; i++)
{
dice1 = rand()%6 + 1;
dice2 = rand()%6 + 1;
diceSum = dice1 + dice2;
if((diceSum == 2) || (diceSum == 3) || (diceSum == 12)){
win++;
}
else if((diceSum == 7) || (diceSum == 11)){
lose++;
}
else{
}
}
cout << "No. of Wins: " << win << endl;
cout << "No. of Losses: " << lose << endl;
cout<< setprecision(4)<<fixed<<showpoint;
cout << "\nThe experimental probability of winning "<< (static_cast<float>(win)/n)*100 <<
"%.\n";
return 0;
}
My assignments states that "...can be shown analytically that the long term probability of winning the dice game you have programmed in PA 8-3 is .4929293. Extend that program you wrote to run a large number of turns and calculate the empirical (experimental) probability." My last assignment I had to make a program to roll two die and reveal the dice sum. If it was a 2, 3, or 12, I won; if it was a 7 or 11 it was a loss, otherwise it would repeat the roll. I was unable to repeat the roll, now for this assignment, I have to do the same thing.This is my output from my current code
I you want to not take into account the cases where the sum is not 2,3,12,7 or 11 you have lot of possibilities, for instance :
closer to your code do i -=1; in the empty else {}
for (int i = 1; i <= n; i++)
{
dice1 = rand()%6 + 1;
dice2 = rand()%6 + 1;
diceSum = dice1 + dice2;
if((diceSum == 2) || (diceSum == 3) || (diceSum == 12)){
win++;
}
else if((diceSum == 7) || (diceSum == 11)){
lose++;
}
else{
i -= 1;
}
}
or increment i only when you win or lose and remove i++ in the for()
for (int i = 1; i <= n;)
{
dice1 = rand()%6 + 1;
dice2 = rand()%6 + 1;
diceSum = dice1 + dice2;
if((diceSum == 2) || (diceSum == 3) || (diceSum == 12)){
win++;
i++;
}
else if((diceSum == 7) || (diceSum == 11)){
lose++;
i++;
}
}
or the variant
i = n;
for (;;)
{
dice1 = rand()%6 + 1;
dice2 = rand()%6 + 1;
diceSum = dice1 + dice2;
if((diceSum == 2) || (diceSum == 3) || (diceSum == 12)){
win++;
if (!--i)
break;
}
else if((diceSum == 7) || (diceSum == 11)){
lose++;
if (!--i)
break;
}
}
or remove all about i and replace your for by do { dice1 = ..... } while ((win + lose) != n); without having the last else branch
do {
dice1 = rand()%6 + 1;
dice2 = rand()%6 + 1;
diceSum = dice1 + dice2;
if((diceSum == 2) || (diceSum == 3) || (diceSum == 12)){
win++;
}
else if((diceSum == 7) || (diceSum == 11)){
lose++;
}
} while ((win + lose) != n);
or the variant
for (;;) {
dice1 = rand()%6 + 1;
dice2 = rand()%6 + 1;
diceSum = dice1 + dice2;
if((diceSum == 2) || (diceSum == 3) || (diceSum == 12)){
if ((++win + lose) == n)
break;
}
else if((diceSum == 7) || (diceSum == 11)){
if ((++lose + win) == n)
break;
}
}
Example of execution whatever the way :
pi#raspberrypi:/tmp $ ./a.out
How many turns would you like? 1000
No. of Wins: 336
No. of Losses: 664
The experimental probability of winning 33.6000%.
This result it normal even it seems opposite of the intuition because the possibilities to make these numbers are :
2 : 1+1
3 : 1+2 2+1
12 : 6+6
and
7: 1+6 6+1 2+5 5+2 3+4 4+3
11 : 5+6 6+5
so 4 possibilities to win ( 1/3/12 ) and 8 possibilities to lose ( 7/11 ), so the probability to lose if two times more than the probability to win
I encourage you to always check the input, replacing
cin >> n;
by something like
if (!(cin >> n)) {
cerr << "invalid number" << endl;
return -1;
}

Renaming filenames in two directories IF certain characters between them match - vector subscript out of range

My first job as an intern was to write a program to compare certain characters in the filenames of two different directories, and if they match, rename them. I wrote a custom code to match the characters. The initial few files get renamed in both directories, but it breaks after a point, giving a vector subscript out of range error.
I have an idea of how to fix such a vector range error from all the other posts, but nothing seemed to work. Any input would be appreciated!
PS: I am not a coder and this is my third official program. I understand the code is a bit messy.
Here is the code:
#include<dirent.h>
#include<vector>
#include<sstream>
int main()
{
cout << "Comparer - Renamer v.0.1.beta\n\n";
string dr1, dr2;
int x, y;
DIR *d1;
struct dirent *dir1;
vector<string> a;
a.reserve(25000);
int i = 0;
cout << "Enter the first directory (format : log_2017...) : ";
cin >> dr1;
d1 = opendir(dr1.c_str());
if (d1){
while ((dir1 = readdir(d1)) != NULL){
i++;
a.push_back(dir1->d_name);
}
closedir(d1);
}
x = a.size();
cout << "\nEnter the second directory (format : 2017.12...) : ";
cin >> dr2;
DIR *d2;
struct dirent *dir2;
vector<string> b;
b.reserve(25000);
int j = 0;
d2 = opendir(dr2.c_str());
if (d2){
while ((dir2 = readdir(d2)) != NULL){
j++;
b.push_back(dir2->d_name);
}
closedir(d2);
}
y = b.size();
ostringstream osa, nsa, osb, nsb;
string oldname_a, newname_a, oldname_b, newname_b;
int u, v, w;
for (int l = 2; l < x; l++){
for (int k = l; k < y; k++){
int c = a[l][20] * 10 + a[l][21];
int d = b[k][14] * 10 + b[k][15];
int e = a[l][17] * 10 + a[l][18];
int f = b[k][11] * 10 + b[k][12];
if (a[l][4] == b[k][0] && a[l][5] == b[k][1] && a[l][6] == b[k][2] && a[l][7] == b[k][3] && a[l][9] == b[k][5] && a[l][10] == b[k][6] && a[l][12] == b[k][8] && a[l][13] == b[k][9]){
u = 0;
}
else{
u = 1;
}
if ((e - f) == 0 && abs(c - d) < 12){
v = 0;
}
else{
v = 1;
}
if ((e - f) == 1 && ((c == 58) || (c == 59) || (c == 0) || (c == 1) || (c == 2))){
w = 0;
}
else{
w = 1;
}
if (u == 0 && (v == 0 || w == 0)){
osa.str(string());
osa << dr1 << "\\" << a[l];
nsa.str(string());
nsa << dr1 << "\\" << l - 1 << ". " << a[l];
oldname_a = osa.str();
newname_a = nsa.str();
osb.str(string());
osb << dr2 << "\\" << b[k];
nsb.str(string());
nsb << dr2 << "\\" << l - 1 << ". " << b[k];
oldname_b = osb.str();
newname_b = nsb.str();
rename(oldname_a.c_str(), newname_a.c_str())
rename(oldname_b.c_str(), newname_b.c_str())
break;
}
}
}
return 0;
}
Presently the code is set such that it shows me how the comparison between the filenames is made.
It turns out I was not debugging properly, and the problem was in this part of the code:
int c = a[l][20] * 10 + a[l][21];
int d = b[k][14] * 10 + b[k][15];
int e = a[l][17] * 10 + a[l][18];
int f = b[k][11] * 10 + b[k][12];
I did not know that I couldn't assign an integer from a string/char directly to an int. I converted the char to int (which would give me the ASCII value of the char) and then subtracted it by 48 to convert it to decimal (I do not know if there is an easier way to do this, but this seemed to have worked for me!) The modified part looks like this:
c = ((int)a[l][20] - 48) * 10 + ((int)a[l][21] - 48);
d = ((int)b[k][14] - 48) * 10 + ((int)b[k][15] - 48);
e = ((int)a[l][17] - 48) * 10 + ((int)a[l][18] - 48):
f = ((int)b[k][11] - 48) * 10 + ((int)b[k][12] - 48);
There was also a small manual error in the conditions, which I also rectified.

Convert string of hexadecimal to decimal in c

I am writing an operating system in C and assembly, and in implementing the EXT2 file system I have encountered a problem. I need to convert FOUR bytes of hexadecimal to decimal in c. An example would be to convert 00 00 01(10000) to 65536.I need to convert to decimal,because parsing the super block requires all values to be in decimal. Most specifically the ext2 fs I'm working on is here:
#include "ext2.h"
#include <stdlib.h>
long hex2dec(unsigned const char *hex){
long ret = 0;
int i = 0;
while(hex[i] != 0){
//if(hex[i] >= 0x00 && hex[i] <= 0x09)
// ret+=(10 * i) * hex[i];
}
//kprintf("\n");
return ret;
}
char *strsep(char *buf,int offset,int num){
char *ret = malloc(1024);
int j = 0;
int i = offset;
int end = (offset + num);
int i1 = 0;
while(i1 < num){
///kstrcat(ret,&buf[i]);
ret[i1] = buf[i];
i++;
i1++;
}
return ret;
}
int get_partition(partnum){
if(partnum > 4)
return -1;
//int i = (12 * partnum);
int i = 0;
if(partnum == 1)
i = 190;
else if(partnum == 2)
i = 206;
else if(partnum == 3)
i = 222;
else
i = 190;
int ret = 0;
char *buf = malloc(1024);
ata_read_master(buf,1,0x00);
ret = buf[(i + 2)];
return ret;
}
int _intlen(int i){
int ret = 0;
while(i){
ret++;
i/=10;
}
return ret;
}
int _hex2int(char c){
if(c == '0')
return 0;
else if(c == '1')
return 1;
else if(c == '2')
return 2;
else if(c == '3')
return 3;
else if(c == '4')
return 4;
else if(c == '5')
return 5;
else if(c == '6')
return 6;
else if(c == '7')
return 7;
else if(c == '8')
return 8;
else if(c == '9')
return 9;
else if(c == 'A')
return 10;
else if(c == 'B')
return 11;
else if(c == 'C')
return 12;
else if(c == 'D')
return 13;
else if(c == 'E')
return 14;
else if(c == 'F')
return 15;
}
int hex2int(char c){
int i = c;
}
int comb(const char *str,int n){
int i = 0;
int ret = 0;
while(i < n){
//if(str[i] == 0x01)
// kprintf("(:");
/*int j = str[i];
int k = 0;
int m = 0;
if(j < 10)
j*=10;
else
while(j > 0){
k+=(10 ^ (_intlen(j) - m)) * j % 10;
m++;
j/=10;
}
//kprintf("%d",j);
//if(j == 1)
// kprintf("(:");*/
i++;
}
//ret = (char)ret;
ret = (char)str
int ret = 0;
int i = 0;
char *s = malloc(1024);
/*while(i < n){
//kstrcat(s,&((char*)buf[i]));
n++;
}*/
return ret;
//kprintf("\n");
//return ret;
}
struct ext2_superblock *parse_sblk(int partnum){
int i = get_partition(partnum);
if(i > 0)
kprintf("[EXT2_SUPERBLOCK]Found partition!\n");
else
i = 0;
struct ext2_superblock *ret;
struct ext2_superblock retnp;
char *buf = malloc(1024);
int i1 = 0;
//char *tmpbuf = malloc(4);
/*if(i != 0)
ata_read_master(buf,((i * 4)/256),0x00);
else{
kprintf("[WRN]: Looking for superblock at offset 1024\n");
ata_read_master(buf,4,0x00);
}*/
ata_read_master(buf,2,0x00);
const char *cmp = strsep(buf,0,4);
retnp.ninode = comb(strsep(buf,0,4),4);
retnp.nblock = comb(strsep(buf,4,4),4);
retnp.nsblock = comb(strsep(buf,8,4),4);
retnp.nunallocb = comb(strsep(buf,12,4),4);
retnp.nunalloci = comb(strsep(buf,16,4),4);
retnp.supernum = comb(strsep(buf,20,4),4);
retnp.leftshiftbs = comb(strsep(buf,24,4),4);
retnp.leftshiftfs = comb(strsep(buf,28,4),4);
retnp.numofblockpg= comb(strsep(buf,32,4),4);
// retnp.numofffpbg= comb(strsep(buf,36,4));
retnp.numoffpbg = comb(strsep(buf,36,4),4);
retnp.numofinpbg = comb(strsep(buf,40,4),4);
retnp.lastmount = comb(strsep(buf,44,4),4);
retnp.lastwrite = comb(strsep(buf,48,4),4);
retnp.fsckpass = comb(strsep(buf,52,2),2);
retnp.fsckallow = comb(strsep(buf,54,2),2);
retnp.sig = comb(strsep(buf,56,2),2);
retnp.state = comb(strsep(buf,58,2),2);
retnp.erroropp = comb(strsep(buf,60,2),2);
retnp.minorpor = comb(strsep(buf,52,2),2);
retnp.ptimefsck = comb(strsep(buf,64,4),4);
retnp.inter = comb(strsep(buf,68,4),4);
retnp.osid = comb(strsep(buf,72,4),4);
retnp.mpv = comb(strsep(buf,76,4),4);
retnp.uid = comb(strsep(buf,80,2),2);
retnp.gid = comb(strsep(buf,82,2),2);
ret = &retnp;
return ret;
i1 = 0;
}
If there is anyway of avoiding conversion and successfully implementing ext2 I would be glad to hear it. I would prefer it to be in c,but assembly is also okay.
If you have this:
const uint8_t bytes[] = { 0, 0, 1 };
and you want to consider that the bytes of a (24-bit) unsigned integer in little-endian order, you can convert to the actual integer using:
const uint32_t value = ((uint32_t) bytes[2] << 16) | (bytes[1] << 8) | bytes[0];
This will set value equal to 65536.
You can use std::istringstream or sscanf instead of writing your own.
char const * hex_text[] = "0x100";
const std::string hex_str(hex_text);
std::istringstream text_stream(hex_str);
unsigned int value;
text_stream >> std::ios::hex >> value;
std::cout << "Decimal value of 0x100: " << value << "\n";
Or using sscanf:
sscanf(hex_text, "0x%X", &value);
std::cout << "Decimal value of 0x100: " << value << "\n";
A good idea is to search your C++ reference for existing functions or search the internet, before writing your own.
To roll your own:
unsigned int hex2dec(const std::string& hex_text)
{
unsigned int value = 0U;
const unsigned int length = hex_text.length();
for (unsigned int i = 0; i < length; ++i)
{
const char c = hex_text[i];
if ((c >= '0') && (c <= '9'))
{
value = value * 16 + (c - '0');
}
else
{
c = toupper(c);
if ((c >= 'A') && (c <= 'Z'))
{
value = value * 16 + (c - 'A') + 10;
}
}
}
return value;
}
To convert to use C-style character strings, change the parameter type and use strlen for the length.

Having trouble casting a stack object number to int (Java)

I'm writing a program that converts an expression from infix to postfix. I have the conversion part down but when it comes to evaluating the postfix expression, I run into problems with converting from char to int using the stack.
I keep getting the error: "Exception in thread "main" java.lang.ClassCastException: java.lang.Character cannot be cast to java.lang.Integer"
It might be in this part of the code below where the problem is but I'm not sure:
Integer x1 = (Integer)stack2.pop();
Integer x2 = (Integer)stack2.pop();
Thank you!
public class Calc {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
System.out.println("Please enter your infix expression: ");
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
String postfix = "";
Stack<Character> stack = new Stack<Character>();
for(int i = 0; i < input.length(); i++){
char subject = input.charAt(i);
if (subject == '*'||subject == '+'||subject == '-'||subject == '/'){
while ((stack.empty() == false) && (order(stack.peek()) >= order(subject)))
postfix += stack.pop() + " ";
stack.push(subject);
}
else if(subject == '(')
{
stack.push(subject);
}
else if(subject == ')')
{
while(stack.peek().equals('(') == false){
postfix += stack.pop() + " ";
}
stack.pop();
}
else{
if((Character.isDigit(subject) == true) && ((i + 1) < input.length()) && (Character.isDigit(input.charAt(i+1)) == true))
{
postfix += subject;
}
else if(Character.isDigit(subject))
{
postfix += subject + " ";
}
else
{
postfix += subject;
}
}
}
postfix += stack.pop();
System.out.println("Your post-fix expression is: " + postfix);
char subject2;
int yeah;
Stack stack2 = new Stack();
for (int j = 0; j < postfix.length(); j++){
subject2 = postfix.charAt(j);
if(Character.isDigit(subject2) == true){
stack2.push(subject2);
}
if(subject2 == ' '){
continue;
}
else{
Integer x1 = (Integer)stack2.pop();
Integer x2 = (Integer)stack2.pop();
if (subject2 == '+'){
yeah = x1 + x2;
}
if (subject2 == '-'){
yeah = x1 - x2;
}
if (subject2 == '*'){
yeah = x1 * x2;
}
if (subject2 == '/'){
yeah = x1 / x2;
}
else {
yeah = 0;
}
}
}
yeah = (int) stack2.pop();
System.out.println("The result is:" + yeah);
}
static int order(char operator)
{
if(operator == '+' || operator =='-')
return 1;
else if(operator == '*' || operator == '/')
return 2;
else
return 0;
}
}
You can solve this by casting to int. Note that int and Integer are not the same:
Integer x1 = (int) stack2.pop();
Integer x2 = (int) stack2.pop();
no casting is necessary by using type-information
Stack<Integer> stack2 = new Stack<Integer>();
…
if(Character.isDigit(subject2) == true){
stack2.push( Character.getNumericValue( subject2 ) );
}
…
to prevent an empty stack exception I'd prefer poll over pop
so it is easier to check an error condition
eg. if( x1 == null ) System.err.println( "Your error message" );
Deque<Integer> stack2 = new ArrayDeque<Integer>();
…
Integer x1 = stack2.poll();
Integer x2 = stack2.poll();
…
btw: the program is syntactically wrong, because it puts only one value on the stack

Algorithm to calculate sum of LUCKY FACTOR in given range

Problem Statement :-
A number is given, N, which is given in binary notation, and it
contains atmost 1000000 bits. You have to calculate the sum of LUCKY
FACTOR in range from 1 to N (decimal notation).
Here, LUCKY FACTOR means, (after converting into binary representation) if
rightmost or leftmost 1's neighbour is either 0 or nothing(for
boundary bit).
EDITED :-
Means if rightmost one's left neighbour is 0, means it count as a
LUCKY FACTOR, simlarly in the left side also
Example,
5 == 101, LUCKY FACTOR = 2.
7 == 111, LUCKY FACTOR = 0.
13 == 1101, LUCKY FACTOR = 1.
16 == 1110, LUCKY FACTOR = 0.
0 == 0, LUCKY FACTOR = 0.
Answer must be in binary form
I am totally stuck, give me a hint.
My code
#include<stdio.h>
#include<string>
#include<string.h>
#include<vector>
//#include<iostream>
using namespace std;
vector<string> pp(10000001);
string add(string a, string b) {
if(b == "") return a;
string answer = "";
int c = 0;
int szeA = a.size() - 1;
int szeB = b.size() - 1;
while(szeA >= 0 || szeB >= 0) {
answer = (char)( ( ( ( (szeA >= 0) ? (a[szeA] - 48) : 0 ) ^ ( (szeB >= 0) ? (b[szeB] - 48) : 0 ) ) ^ (c) ) + 48 ) + answer;
c = ( ( ( (szeA >= 0) ? (a[szeA] - 48) : 0 ) & ( (szeB >= 0) ? (b[szeB] - 48) : 0 ) ) | ( ( (szeA >= 0) ? (a[szeA] - 48) : 0 ) & (c) ) | ( ( (szeB >= 0) ? (b[szeB] - 48) : 0 ) & (c) ) );
szeA--;
szeB--;
}
if(c) answer = '1' + answer;
return answer;
}
string subtract(string a, string b) {
int sze = a.size() - b.size();
while(sze--) b = '0' + b;
sze = a.size();
for(int i = 0; i < sze; i++) {
if(b[i] == '1') b[i] = '0';
else b[i] = '1';
}
if(b[sze-1] == '0') {
b[sze-1] = '1';
}
else {
int i = sze-1;
while(i >= 0 && b[i] == '1') {
b[i] = '0';
i--;
}
if(i >= 0) b[i] = '1';
else b = '1' + b;
}
b = add(a, b);
b.erase(b.begin() + 0);
//b[0] = '0';
while(b[0] == '0') b.erase(b.begin() + 0);
return b;
}
string power(int index) {
if(index < 0) return "";
string answer = "";
while(index--) {
answer = '0' + answer;
}
answer = '1' + answer;
return answer;
}
string convert(long long int val) {
int divisionStore=0;
int modStore=0;
string mainVector = "";
do {
modStore=val%2;
val=val/2;
mainVector = (char)(modStore+48) + mainVector;
}while(val!=0);
return mainVector;
}
string increment(string s) {
int sze = s.size()-1;
if(s[sze] == '0') {
s[sze] = '1';
return s;
}
while(sze >= 0 && s[sze] == '1') {
s[sze] = '0';
sze--;
}
if(sze >= 0) s[sze] = '1';
else s = '1' + s;
return s;
}
main() {
int T;
char s[1000001];
string answer;
scanf("%d", &T);
for(int t = 1; t <= T; t++) {
int num;
answer = "1";
int bitComeEver = 0;
int lastBit = 0;
scanf("%s", s);
int sze = strlen(s);
// I used below block because to avoid TLE.
if(sze > 3300) {
printf( "Case #%d\n", t);
for(int i = 0; i < sze; i++) printf("%c", '1');
printf("\n");
//continue;
}
else {
if(pp[sze-1] != "") answer = pp[sze-1];
else {
pp[sze-1] = power(sze-1);
answer = pp[sze-1];
}
answer = subtract(answer, convert(sze-1));
////////////////////////////
//cout << answer << endl;
for(int i = 1; i < sze; i++) {
if(s[i] == '1') {
if(s[1] == '0') {
num = sze-i-1;
if(num > 0) {
if( pp[num-1] == "") {
pp[num-1] = power(num-1);
}
if(pp[num+1] == "") {
pp[num+1] = power(num+1);
}
answer = add(answer, subtract(pp[num+1], pp[num-1]));
if(lastBit) answer = add(answer, "1");
//else answer = increment(answer);
//cout << "\t\t" << answer << endl;
}
else{
int inc;
if(lastBit) inc = 2; //answer = add(answer, "10");
else inc = 1; //answer = increment(answer);
if(s[i-1] == '0') lastBit = 1;
else lastBit = 0;
if(lastBit) inc += 2;
else inc += 1;
if(inc == 2) answer = add(answer, "10");
else if(inc == 3) answer = add(answer, "11");
else answer = add(answer, "100");
}
}
else {
if(num > 0) {
if(pp[num-1] != "") pp[num-1] = power(num-1);
answer = add(answer, pp[num-1]);
}
else {
int inc = 0;
if(lastBit) inc = 1; //answer = increment(answer);
if(s[i-1] == '0') lastBit = 1;
else lastBit = 0;
if(lastBit) inc += 1;
answer = add(answer, convert(inc));
}
}
if(s[i-1] == '0') lastBit = 1;
else lastBit = 0;
}
}
if(s[sze-1] == '0') {
if(lastBit) {
if(s[1] == '0') {
answer = add(answer, "10");
}
else answer = increment(answer);
}
else if(s[1] == '0'){
answer = increment(answer);
}
}
printf( "Case #%d\n", t);
for(int i = 0; i < sze; i++) printf("%c", answer[i]);
printf("\n");
}
}
return 0;
}
If a number has k bits, then calculate the number of such numbers having a LUCKY FACTOR of 2:
10.............01
Hence in this the 1st two and last two digits are fixed, the remaining k-4 digits can have any value. The number of such numbers = 2^(k-4).
So you can easily calculate the sum of lucky factors of such numbers = lucky_factor x 2^(k-4)
(ofcourse this is assuming k >= 4)
What's more, you do not need to calculate this number since it will be of the form 10000000.
If the number n is 11010010. Then 8 bit numbers less than n shall be of form:
10........ or 1100...... or 1101000_. If you see a pattern, then we have divided the calculation in terms of the number of 1s in the number n
.
I leave the rest for you.