Create a shifter
APL (Dyalog), 32 bytes
Anonymous function which takes the sift as left argument and the number (as a string) as right argument.
{a←|⍺⋄(≢⍵)↑(a-⍺)↓(a⍴⊃⍵),⍵,a⍴⊃⌽⍵}
Try it online!
{
anonymous function where ⍺ and ⍵ are left and right arguments
|⍺
the absolute value of the shift
a←
store in a
⋄
then
⌽⍵
reverse the number
⊃
pick the first (i.e. last) digit
a⍴
reshape it to length a
⍵,
prepend the number
(
…),
prepend the following:
⊃⍵
the first digit
a⍴
reshape it to length a
(
…)↓
drop the following number of characters:
a-⍺
a minus the shift
(
…)↑
take the following number of characters:
≢⍵
the length of the original number
Python 2, 50 bytes
lambda n,s:(n[0]*s+n+n[-1]*-s)[-s*(s<0):][:len(n)]
Try it online!
MATL, 12 bytes
tn:i-yn1&Xl)
Inputs are: number to be shifted as a string; amount of shifting as a number.
Try it online! Or verify all test cases.
Consisder inputs '452
and '-1'
.
t % Implicitly input string. Duplicate
% STACK: '452', '452'
n % Number of elements
% STACK: '452', 3
: % Range
% STACK: '452', [1 2 3]
i % Input number
% STACK: '452', [1 2 3], -1
- % Subtract, element-wise
% STACK: '452', [2 3 4]
y % Duplicate from below
% STACK: '452', [2 3 4], '452'
n % Number of elements
% STACK: '452', [2 3 4], 3
1 % Push 1
% STACK: '452', [2 3 4], 3, 1
&Xl % Clamp, with three inputs. Applies min function, then max
% STACK: '452', [2 3 3]
) % Reference indexing. Implicitly display
% STACK: '522'