10

Here is the code:

#include <iostream>
using namespace std;

int main ()
{
    int n;
    cin >> n;
    int first = n;

    while (first>=10)
    {
      first/=10;
    }

    cout << first << endl;
}

In the above code that I tried to get the first digit of a positive number, what I want to do is to put it after the last digit like this, for example: 1934 -> 9341.

Feathercrown
  • 2,547
  • 1
  • 16
  • 30
Derek Cole
  • 135
  • 1
  • 3

15 Answers15

18

Convert the number to a string using std::to_string, perform the left rotation using std::rotate and convert back to a number using std::stoull function:

std::string s = std::to_string(n);
std::rotate(s.begin(), s.begin() + 1, s.end());
n = std::stoull(s);

With all the headers included:

#include <iostream>
#include <string>
#include <algorithm>

int main() {
    unsigned long long n = 1934;
    std::string s = std::to_string(n);
    std::rotate(s.begin(), s.begin() + 1, s.end()); // left rotation
    n = std::stoull(s);
    std::cout << n; // 9341
}
Ron
  • 14,674
  • 4
  • 34
  • 47
12

Here is a simple solution that does not use strings or floating point functions / arithmetic. The usage of functions such as pow() may run into problems as outlined in this question.

 #include <iostream>

 int main()
 {
    unsigned long long n = 1934L;

    // save the original
    unsigned long long final_number = n;

    // multiplying factor
    unsigned long long mult = 1;

    // start by making sure we do not loop one too many times to 
    // calculate the multiplier
    n /= 10;

    while (n > 0)
    {
        // determines the multiplication factor after the loop 
        mult *= 10; 

        // strip off digit from number
        n /= 10;
    }

    // create the final number from the original and the multiplication factor
    final_number = (final_number % mult) * 10 + final_number / mult;
    std::cout << final_number << "\n";
}

Live Example

Basically we count how many digits by looping, and at the same time increase the multiplying factor by 10. Then after the loop, the number is constructed by using modulus, multiplication, division, and addition.

So for example, after the loop, the final_number would be

(1934 % 1000) * 10 + 1934 / 1000 =
934 * 10 + 1934 / 1000 = 
9340 + 1934 / 1000 =
9340 + 1 =
9341

Note: I looked at the generated assembly language here and was amazed that the compiler is able to figure out the intent of the code, and computed 9341 at compile-time. I doubt the pow solutions or floating point methods would produce these results.

PaulMcKenzie
  • 34,698
  • 4
  • 24
  • 45
7

You can modify your loop to not only get the first digit, but also compute the number of digits at the same time (it's the number of the loop's iterations). Then, use % and * 10 as appropriate to modify n.

Angew is no longer proud of SO
  • 167,307
  • 17
  • 350
  • 455
4

Suppose we have positive integer as input.

  1. Get the most significant digit

    MSD=floor(X/pow(10,floor(log10(X))));
    
  2. Get the rest of the number

    Rest=X%pow(10,floor(log10(X)));
    
  3. Raising the rest to appropriate value

    Rest=Rest*10;
    
  4. Adding the former most significant digit

    Y=Rest+MSD.
    

Exploded example:

X=54321;                             // 54321
                         log10(X)    // 4.734...
                   floor(...     )   // 4
            pow(10,...            )  // 10000
          X/...                      // 5.4321
MSD=floor(...                      );// 5
           pow(10,floor(log10(X))    // 10000
         X%...                       // 4321
      10*...                         // 43210
Y=MSD+...                        ;   // 43215
Crowley
  • 2,279
  • 6
  • 22
  • 36
  • Uhh, isn't `^` [Bitwise XOR](http://en.cppreference.com/w/cpp/language/operator_arithmetic#Bitwise_logic_operators)? Did you mean to use `pow()`? – Drise Feb 02 '18 at 19:41
  • @Drise Thanks for pointing out. I am used to different language. Also, as Phillip Schmid uses, C-based languages turncate integers by default, so `floor()` is not needed, but I use it as language independent answer. `^` is power in MATLAB, what I am using mostly... – Crowley Feb 02 '18 at 19:48
  • 1
    Actually, if I'm not mistaken, 'rounds integer [division] down' isn't what you're looking for in C/C++, it's [truncation towards zero](https://stackoverflow.com/questions/3602827/what-is-the-behavior-of-integer-division) – Drise Feb 02 '18 at 19:51
  • `MSD=floor(X/pow(10,floor(log10(X))));` is mathematically correct, yet computationally prone to round off error for values of `X` near `D * some_power_of_10` or when `X` is more precise (e.g. 64-bit) than `double`. – chux - Reinstate Monica Feb 09 '18 at 15:08
4

A solution that does not use strings. It does use std::stack, and it may not win any efficiency awards, but it should be quite straightforward and understandable.

#include <stack>
#include <iostream>

int main()
{
    int num = 1934;
    std::stack<int> digits;

    // Break the number into digits, pushing them onto a stack
    while (num)
    {
        auto digit = num % 10;
        digits.push(digit);
        num /= 10;
    }

    // Get the first digit from the top of the stack and save it
    auto first = 0;
    if (!digits.empty())
    {
        first = digits.top();
        digits.pop();
    }

    // Pop the remaining digits off the stack and print them
    while (!digits.empty())
    {
        std::cout << digits.top();
        digits.pop();
    }

    // Print the first digit on the end
    std::cout << first << '\n';
}

EDIT: Fixed bug if num == 0. Note that negative numbers are not handled correctly, but I'm not sure what the desired behavior would be for that case. Using unsigned instead of int might be a good idea.

Fred Larson
  • 60,987
  • 18
  • 112
  • 174
4

I'll start off by saying I'm not a c++ programmer; so I'm not saying this code is good, just that it works and it follows your approach!

I'm going to walk you through the how before I show you a minimal edit of your code to get what you want, with an example: we'll assume you want to convert 2345 into 3452

  • You've started off by finding the most significant digit (first) of your input (n)
  • You now need to remove that digit from the front. This is easy:
    • We already have a loop where we divide first by 10, so let's reuse it
    • create a number (we'll call it bigness) that starts at 1, and every loop, multiply it by 10.
  • You now have 3 numbers:
    • n = 2345
    • first = 2
    • bigness = 1000

That's all you need!

You can subtract first * bigness from n to remove the number from the front - 345

You can multiply that by 10 and add first to place the number on the end - 3452

Here's the end code:

#include <iostream>
using namespace std;

int main ()
{
    int n;
    cin >> n;
    int first = n;
    int bigness = 1;

    while (first >= 10)
    {
        first /= 10;
        bigness *= 10;
    }

    n = n - (first * bigness);
    n = (n * 10) + first;

    cout << n;
}

Note that this will leave problems for numbers like 20000 - they become 2, because our code doesn't know we want 00002. This is easy to fix using something like printf to maintain the number of digits, but that will mean another variable in your loop, starting at 1, counting the number of digits we need.

user208769
  • 2,216
  • 1
  • 18
  • 27
  • `(n * 10) + first;` may overflow for starting values like `n = 1987654321`. – chux - Reinstate Monica Feb 09 '18 at 15:18
  • 1
    Yep - a downside of using ints. As mentioned in my very first line, I'm not saying it's good code - merely that it follows logically from the OP's starting point. I'm pretty sure this will fail horribly for lots of unintended input - negatives, decimals and non-numeric inputs to say the least. – user208769 Feb 12 '18 at 22:24
4

As C++ integers have at most a dozen or so digits, code could use a simple recursive solution:

unsigned reverse_helper(unsigned x) {
  if (x < 10) {
    return x;
  }
  unsigned last = reverse_helper(x/10);
  cout << x%10;
  return last;
}

void reverse(unsigned x) {
  cout << reverse_helper(x)) << endl;
}

Test code

int main(void) {
  reverse(0);
  reverse(9);
  reverse(10);
  reverse(1934);
  reverse(1234567890);
}

0
9
01
9341
2345678901
chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256
3

as there already a lot of solutions with std::string, I tried to do it without it, here are my results. I hope this helps.

#include <iostream>
#include <cmath>
using namespace std;

int removeFirst(int n)
{
    int tmp(0);
    for (int i(0);; ++i)
    {
        int m = n % 10;
        n /= 10;
        if (n != 0)
        {
            tmp += pow(10, i) * m;
        }
        else
        {
            break;
        }
    }
    return tmp;
}

int main()
{
    int input, first, withoutFirst;
    cin >> input;
    withoutFirst = removeFirst(input);

    while (input >= 10)
    {
        input /= 10;
    }
    first = input;

    cout << withoutFirst << first << endl;
}

Help used: trying to remove first digit of any number

Regards.

BERNARDO
  • 219
  • 2
  • 12
3

Here's a version without using strings.

//There's also a builtin log10 function but you can write your own if you want to:
int log10(int nbr) {
    return log(n) / log(10);
}

//....
int first_digit = n / (int)pow(10, log10(n));
int everything_else = n % (int)pow(10, log10(n));

Make sure to include math.h

It uses the fact that a float -> int conversion always rounds towards zero in C++. So (int)log10(101) will return 2, and pow(10, (log10(n))) will therefore round every number rounded down to 10/100/1000/etc. The rest is just simple division and modulo.

CookedCthulhu
  • 744
  • 5
  • 14
  • I've added a comment that there's also a builtin `log10` function if that was your critique. If that wasn't your point, please elaborate. The solution should be a lot faster than any of the answers which use strings – CookedCthulhu Feb 02 '18 at 16:13
  • Maybe wrap the pow() in floor() just to make it explicit? – Mick O'Hea Feb 05 '18 at 12:34
  • Both `log(n)` and `log(10)` return approximate mathematical results of the true math _log_. Conversion to `int` of results from transcendental functions like `log(), exp()` may return unexpectedly `int` from `x.9999999999999...` Use of FP for an _integer_ problem invites corner case and portability problems. – chux - Reinstate Monica Feb 09 '18 at 15:15
3

This is a typical element of programming and math+programming contests, so I will not give a complete answer, but I will say that:

  • Using strings is almost certainly not the most cpu-time efficient solution.
  • You already have the first (most significant) digit. Modifying the code in your question you can compute the appropriate power of 10 to subtract the first digit from the original number.
  • Notice that n * 10 shifts the number left and leaves a "hole" you can later fill as needed. (Apologies if this is obvious to you.)
  • You can do all that using only integer operations, no floats, no functions (log, exp). Other solutions already show complete algorithms; I emphasize you can do without floats and logs.
  • Be careful with 0 and negative numbers.
Pablo H
  • 609
  • 4
  • 22
2

There are already some answers with string and one more answer so far without string. Using string is the most efficient one. But if the OP wanted to solve it by calculative method and using integer, here is what I've tried. When string is not used, in that case, this solution is more efficient I guess.

#include <iostream>
#include <math.h>
using namespace std;

int main ()
{
    int n, digits, firstDigit, firstDigitToLast;
    cin >> n;

    digits = (int)log10(n);
    firstDigit = (int)(n / pow(10, digits));
    firstDigitToLast = n % ((int) pow(10, digits));
    firstDigitToLast *= 10;
    firstDigitToLast += firstDigit;

    cout << firstDigitToLast << endl;
}
UkFLSUI
  • 5,509
  • 6
  • 32
  • 47
1
std::string s = std::to_string(n);
s += s.front();
s.erase(0, 1);
n = std::stoull(s);

This:

  1. Converts the number to a string.
  2. Adds the first character to the end.
  3. Removes the first character.
  4. And converts the result back to an unsigned long long.

Live Example

Arnav Borborah
  • 11,357
  • 8
  • 43
  • 88
1

I would use log10 and %.

int num = 8907;

int num_digits = log10(num); // Value of 3 for 8907
int pwr = pow(10, num_digits); // Value of 1000 for 8907
int ones_place = num % 10; // 7
int bigs_place = num / pwr; // 8

int cur_msd = bigs_place * pwr; // 8000
int new_msd = ones_place * pwr; // 7000

num -= cur_msd;
num += new_msd;
num -= ones_place;
num += bigs_place;
cout << num << endl;

This code outputs 7908 for me.


Edit

I misread the post. I thought you wanted the LSB and MSB swapped, not rotated.

Replace the last 4 lines with

num -= cur_msd;
num *= 10;
num += bigs_place;
DeepDeadpool
  • 1,441
  • 12
  • 36
1

While loops and strings can be very effective, they're quite unnecessary in this case.
All you need is a bit of maths:

#include <math.h>       // log10, pow, floor
#include <stdio.h>      // printf
int main ()
{
  int n = 6945;
  int p = pow(10,floor(log10(n)));
  int output = (n - ((n/p)%10)*p)*10+((n/p)%10);
  printf("%i",output);       // outputs 9456
}

The idea is to first find how many digits the number has (floor(log10(n))), then to get the most significant digit by dividing the input by 10 raised to that power (pow(10,floor(log10(n)))) modulo 10. We will store this in an int called p.

In this case, that gives us 6. We then subtract 6 times p from n to get the remaining digits (945 in our case) which we then multiply by ten and add 6 to, yielding our final answer of 9456

DividedByZero
  • 4,333
  • 2
  • 19
  • 33
0

here is how i did it

#include<stdio.h>
#include<math.h>
int main()
{
int a,g=10,m=1,c,num;
printf("enter the number : ");
scanf("%d",&a);
c=log10(a);
num=num+((a%10)*pow(10,c));
a=a/10;
c=log10(a);
while(m<=c){
    if(m==c){
        num=num+((a%10)*g)+a/10;
        break;
    }
    else{
        num=num+((a%10)*g);
        g=g*10;
        a=a/10;
        m=m+1;
    }
}
printf("%d",num);
}