Remove leading zeroes from Binary converted from Decimal - c++

I am solving a problem where I have to convert given first N natural numbers to binary numbers. I am using bitset and .to_string(). But, after the number is converted to binary it has some leading zeroes obviously as equal to the size of the given bitset. The task is to remove that. I have done that using std::string:: erase() But I think it's not a good approach to do so. How can I optimize this part of the code?
#include <iostream>
#include <bitset>
#include <string>
int main()
{
int T;
std:: cin >> T;
while(T--) {
int n;
std:: cin >> n;
for(auto i = 1; i <= n; ++i) {
std::string binary = std::bitset<32>(i).to_string(); //to binary
//This part here
int j = 0;
while(binary[j] == '0') {
++j;
}
binary.erase(0, j);
//Till here
std::cout<<binary<<" ";
}
std:: cout << std:: endl;
}
return 0;
}

You could make use of the std::string::find_first_not_of() function to get the position of the first character that isn't a zero. Then use std::string::erase() to erase from the beginning of the string (index 0) to the position of the first non-zero character. This will avoid the while loop you're currently using.
Example:
std::string binary = std::bitset<32>(128).to_string(); //"00000000000000000000000010000000"
binary.erase(0, binary.find_first_not_of('0')); //"10000000"
std::cout << binary;

I would suggest to use log2 function from cmath header file. You can count the number of bits you would require to represent the integer in binary format with this. Thus you won't need the while loop used to count the number of leading zeroes.
Here is the code:
#include <iostream>
#include <bitset>
#include <string>
#include <cmath>
int main()
{
int T;
std:: cin >> T;
while(T--) {
int n;
std:: cin >> n;
for(auto i = 1; i <= n; ++i) {
std::string binary = std::bitset<32>(i).to_string(); //to binary
int len = log2(i)+1;
binary.erase(0,32-len);
std::cout<<binary<<"\n";
}
std:: cout << std:: endl;
}
return 0;
}
As john mentioned in the comment section, you not necessarily need to remove the number of leading zeroes. For that you can do this,
std::cout<<binary.substr(32-len,len)<<"\n";

Related

The question is about printing digits of two digit number n, I'm encountering a runtime error

Given a two-digit number n, print both the digits of the number.
Input Format:
The first line indicating the number of test cases T.
Next T lines will each contain a single number ni.
Output Format:
T lines each containing two digits of the number ni separated by space.
Constraints
1 <= T <= 100000
10 <= ni <= 99
Error: Runtime Error (SIGSEGV)
I'm not able to pinpoint, where the problem is in the code as it is working fine for a two numbers while it gives the runtime error for 4 or more numbers.
Is there another way of doing this problem other than using for loop twice?
#include <bits/stdc++.h>
using namespace std;
int main()
{
int t;
int arr[t];
cin>>t;
for(int i=0;i<t;i++)
{
cin>>arr[i];
}
int c;
int b;
for(int i=0;i<t;i++)
{
c=(arr[i]/10);
if(c!=0)
{
b=arr[i]%(c*10);
}
else
{
b=arr[i];
}
cout<<c<<" "<<b<<endl;
}
return 0;
}
Fist, you declare t, but do not initialize it, so it is uninitialized. Trying to use the value leads to undefined behavior.
Second, VLA is not valid C++, see here. You have to use std::vector instead.
Third, you don't need to use an int.
So, you should do:
#include <iostream>
#include <vector>
#include <string>
int main()
{
int t{};
std::cin >> t;
std::vector<std::string> arr(t);
for(int i = 0; i < t; i++)
{
std::cin >> arr[i];
}
for(const auto &i : arr)
{
std::cout << i[0] << ' ' << i[1] << '\n';
}
}

How to know the number of digits in an integer

I'm new to programming, and I'm wondering, how can I know the number of digits in an integer that the user enters? For example: the user enters a number like 123456, how can I know that the user enters 6 digits? I don't want to use a for loop to get user input because I don't want the user to enter each digit after a space or enter.
Right now, I'm converting a number to an array of digits so I can have control over them, but the issue is that I don't know how many digits I should loop over, because I don't know how many digits are in the number.
Can I get the user's input as a string and then use string.length and convert it to an array of digits?
#include <iostream>
using namespace std;
int main()
{
int N;
cin >> N;
while(N--)
{
int num;
cin >> num;
int arr[1000];
for (int i=0 ;i<???;i++)
{
arr.[i]=num%10;
num = num /10;
}
}
}
an easier way to do this is to convert it to a string then count the length of said string
#include <iostream>
#include <string>
using namespace std;
int main() {
int n;
cin >> n;
string str = to_string(n);
cout <<"the length of" <<str << "is:" <<str.length() <<"\n";
}
typing in a 41 will print out.
the length of 41 is 2
while (num != 0)
{
arr.[i]=num%10;
num = num /10;
}
is a common pattern that's close to what you already have.
Although you can do what you mentioned in your question and someone suggested in the comments and get the input as a string and use string.length.
Yes, you can read in the user's input as a std::string instead of as an int, and then you can use std::string::size() (or std::string::length()) to get the number of characters in the string, eg:
#include <iostream>
#include <string>
int main()
{
std::string S;
std::cin >> S;
int arr[1000] = {};
for (size_t i = 0; i < S.size(); ++i)
{
arr[i] = (S[i] - '0');
}
return 0;
}
Alternatively:
#include <iostream>
#include <string>
#include <algorithm>
int main()
{
std::string S;
std::cin >> S;
int arr[1000] = {};
std::transform(S.begin(), S.end(), arr, [](char ch){ return int(ch - '0'); });
return 0;
}
Either way, if needed, you can check if the std::string represents a valid integer using std::stoi() or std::strtol() or other similar function, or by putting the std::string into a std::istringstream and then reading an integer from it.
Otherwise, you can read the user's input as an int and then convert it to a std::string for processing:
#include <iostream>
#include <string>
int main()
{
unsigned int N;
std::cin >> N;
std::string S = std::to_string(N);
int arr[1000] = {};
for (size_t i = 0; i < S.size(); ++i)
{
arr[i] = (S[i] - '0');
}
// or:
// std::transform(S.begin(), S.end(), arr, [](char ch){ return int(ch - '0'); });
return 0;
}
Otherwise, if you really want to read in an int and loop through its digits directly, you can use something more like this:
#include <iostream>
int main()
{
unsigned int N;
std::cin >> N;
int arr[1000] = {};
size_t i = 0;
while (N != 0)
{
arr[i++] = num % 10;
num /= 10;
}
return 0;
}

C++ determinable array input in one line

I'm pretty new to c++ and can't seem to find correct way to code this. I have array of n digits, my code now:
int main()
{
int n,i;
cin >> n;
int a[n];
for (i=1;i<=n;i++)
{
cin >> a[i];
}
return 0;
}
This way every element of array has to be input in different line, is it possible to put all elements of a array in one line, with space between them.
I am assuming your question is "what is the correct way to do this?"
I would do it this way:
#include <iostream>
#include <vector>
using std::cin;
using std::cout;
using std::endl;
using std::vector;
int main()
{
int n;
cin >> n;
vector<int> v;
int i = 0;
int value;
while (i++ < n && cin >> value)
{
v.push_back(value);
}
char const* sep = "";
for (auto item : v)
{
cout << sep << item;
sep = " ";
}
cout << endl;
}
Note that this code is making assumptions that the input is well formed. If you need something that is more robust in handling possibly malicious input, that would require extra effort. This code, as given, will give-up-trying-and-continue which may or may not be suitable for your purposes.
The following code snippet of your program is a Variable Length Array(VLA) and this is only supported in C since ISO C99.
cin >> n;
int a[n];
And as previously pointed out, you can also use std::vector instead.
int main()
{
int size;
std::cin >> size;
int *array = new int[size];
delete [] array;
return 0;
}
References:
http://gcc.gnu.org/onlinedocs/gcc/Variable-Length.html
How to create a dynamic array of integers
Without using stl container , one can implement like so:
#include <iostream>
#include <string>
#include "stdlib.h"
void GetInput(int* inputs, int n)
{
// store the entered numbers in a char[]
std::string word;
std::cout << "enter numbers (separate by space) ";
std::getline(std::cin, word);
char ch[100];
strcpy_s(ch, word.c_str());
char *temp = ch;
// parse the char[] for integers
for (int i = 0; strcmpi(temp, "") != 0 && i <= n; temp++,i++) {
*(inputs +i) = std::strtol(temp, &temp, 10);
}
}
int main()
{
int n = 3;
int inputs[10];
GetInput(inputs,n);
for (int j = 0; j < n; j++)
std::cout << inputs[j] << " \n";
return 0;
}
Output:

Printing an array in reverse

Task
You'll be given an array of N integers and you have to print the integers in the reverse order.
Constraints
1<=N<=1000
1<=A_i<=10000, where A_i is the ith integer in the array.
Input
4
1 2 3 4
Output
4 3 2 1
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
int N, y; //declaring N as the length of array
cin >> N; //intakes the length as an input
if (N>=1 && N<=1000){ //checks whether the length satisfies the rules
int a[N]; // makes an array containing N elements
for (int x =1; x<N; x++){ //starts transcription on the array
cin>>y; //temporarily assigns the input on a variable
if (y>=1&&y<=10000){ //checks if the input meets rules
a[x]=y; //copies the variable on the array
}
}
for (int z = N; z>1; z--){ //runs a loop to print in reverse
cout<<a[z]<<endl;
}
}
return 0;
}
Problem
Obtained output is
-1249504352
3
2
Indicating an error in transcription.
Question
Can somebody please tell me where I am making a mistake? Secondly, is it possible to directly check whether an input is meeting requirement rather than temporarily declaring a variable for it?
Here is a solution in idiomatic c++11, using std::vector, which is a dynamically resizable container useful for applications like this.
#include <vector>
#include <iostream>
#include <algorithm>
int main() {
int size;
std::cin >> size; // take in the length as an input
// check that the input satisfies the requirements,
// use the return code to indicate a problem
if (size < 1 || size > 1000) return 1;
std::vector<int> numbers; // initialise a vector to hold the 'array'
numbers.reserve(size); // reserve space for all the inputs
for (int i = 0; i < size; i++) {
int num;
std::cin >> num; // take in the next number as an input
if (num < 1 || num > 10000) return 1;
numbers.push_back(num);
}
std::reverse(numbers.begin(), numbers.end()); // reverse the vector
// print each number in the vector
for (auto &num : numbers) {
std::cout << num << "\n";
}
return 0;
}
A few things to note:
using namespace std is considered bad practice most of the time. Use (e.g.) std::cin instead for things which come from the std namespace.
numbers.reserve(size) is not necessary for correctness, but will make the program faster by reserving space in advance.
for ( auto &num : numbers ) uses a range-based for loop, available in c++11 and later versions.
You could make your for loop indices go from high to low:
for (int i = N-1; i > 0; --i)
{
std::cout << a[i] << "\n"; // Replace '\n' with space for horizontal printing.
}
std::cout << "\n";
This would apply with std::vector as well.
With std::vector, you can use a reverse iterator. There are other techniques available (as in other answers).

Strings and user input C++

I'm supposed to read an integer n from the user, which is the followed by n words, and then what follows after that is a sequence of words and punctuation terminated by the word END. For example:
2 foo d
foo is just food without the d . END
The n words are to be "redacted" from the second line. So it would show up as:
*** is just food without the * .
I think I can figure out the redacting part. I just cannot seem to figure out how to read the words in... any help is much appreciated!
#include <iostream>
#include <string>
using namespace std;
int main()
{
int n;
cin >> n;
string *redact = new string[n]
for(int i = 0; i < n; ++i)
cin >> redact[i] // this part works!
return 0;
}
Following code will cater the purpose.
#include <iostream>
#include <string>
#include <set>
int main()
{
int n;
std::cin >> n;
std::set<std::string> redact;
std::string word;
for(int i = 0; i < n; ++i)
{
std::cin >> word;
redact.insert(word);
}
while( std::cin>> word && word != "END" )
{
if ( redact.find(word) == redact.end() )
std::cout<<word<<' ';
}
std::cout<<'\n';
return 0;
}
I believe you are a learning C++, please note a point use typesafe, bound-safe and scope-safe C++.
So, no new delete unless you can call yourself an adept. Use the algorithms and containers provided by C++, instead of inventing your own.