ค้นหาจำนวนที่เล็กที่สุดที่ใหญ่กว่าอินพุทที่มีผลรวมดิจิตอลเป็นอินพุท


28

"ผลรวมดิจิตอล" หมายถึงผลรวมของตัวเลขทั้งหมดในจำนวน

ยกตัวอย่างเช่นผลรวมดิจิตอล1324เป็นเพราะ101+3+2+4 = 10

ความท้าทายคือการเขียนโปรแกรม / ฟังก์ชั่นเพื่อคำนวณจำนวนที่เล็กที่สุดที่ใหญ่กว่าอินพุทที่มีผลรวมดิจิตอลเป็นอินพุท

ตัวอย่างที่มีคำแนะนำแบบ

ยกตัวอย่างเช่นใช้ตัวเลข9เป็นอินพุต:

9 = 1+8 -> 18
9 = 2+7 -> 27
9 = 3+6 -> 36
...
9 = 8+1 -> 81
9 = 9+0 -> 90

18เอาท์พุทที่ถูกต้องจะเป็นจำนวนที่น้อยที่สุดดังกล่าวข้างต้นซึ่งเป็น

รายละเอียด

โปรดทราบว่า9ไม่ใช่เอาต์พุตที่ถูกต้องสำหรับตัวอย่างนี้เนื่องจากหมายเลขที่กลับจะต้องมากกว่าจำนวนเดิม

โปรดทราบว่าอินพุตจะเป็นค่าบวก

การทดสอบกรณี:

 2 => 11      (2 = 1 + 1)
 8 => 17      (8 = 1 + 7)
12 => 39     (12 = 3 + 9)
16 => 79     (16 = 7 + 9)
18 => 99     (18 = 9 + 9)
24 => 699    (24 = 6 + 9 + 9)
32 => 5999   (32 = 5 + 9 + 9 + 9)

อ้างอิง:

นี่คือOEIS A161561

แก้ไข:เพิ่ม Testcase เพิ่มเติม (18)

ขอบคุณMartin Enderสำหรับตัวอย่างกระดานผู้นำ

var QUESTION_ID=81047,OVERRIDE_USER=31373;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table>


11
ชื่อนี้ทำให้สมองของฉันเจ็บ
ทำให้เสียชีวิต

คำตอบ:


4

05AB1E, 19 17 8 ไบต์

รหัส:

[>DSO¹Q#

อธิบาย:

[            # start infinite loop
 >           # increase loop variable, will initially be input
  DSO        # make a copy and sum the digits
     ¹Q#     # if it equals the input, break
             # else return to start of loop
             # implicitly print

ลองออนไลน์

แก้ไข:บันทึกแล้ว 9 ไบต์ขอบคุณ @Adnan


4
SOเป็นวิธีที่สั้นกว่าในการรับผลรวมของตัวเลข (แทนJ`)O) นอกจากนี้หากไม่มีการกำหนดตัวแปรคุณสามารถทำได้[>DSO¹Q#:)
Adnan

2
@Adnan ดี! ฉันพลาดเอสไปทั้งหมดน่าจะรู้ว่าฉันไม่ต้องการตัวแปร
Emigna

14

Python 2, 33 ไบต์

lambda n:[n+9,`n%9`+n/9*'9'][n>9]

การแสดงออกโดยตรง ทำให้สตริงตัวเลขมีค่า 9 ในตอนท้ายและส่วนที่เหลืออยู่ที่จุดเริ่มต้น ยกเว้นสำหรับหลักเดียวให้nn+9

เอาต์พุตบางตัวมีศูนย์นำหน้า ( 099สำหรับ18)


7

เรติน่า39 39ไบต์

r`1{1,9}
$.&
T`d`_d`^.$
^.$
1$&

จะเข้าในเอก

ลองออนไลน์! (สองบรรทัดแรกอนุญาตให้เรียกใช้หลายกรณีทดสอบในคราวเดียวและแปลงจากเลขฐานสิบเป็น unary เพื่อความสะดวก)

สิ่งนี้ไม่ได้ค้นหาผลลัพธ์เชิงเส้น แต่คำนวณอย่างชัดเจน:

  • หากอินพุตnมากกว่า 9 เราจะแทนที่ด้วยเก้า ( n % 9ตามn / 9พื้น)
  • n + 9มิฉะนั้นเราจะแทนที่ด้วย

การใช้!(หรือสิ่งอื่นที่ไม่ใช่1) เป็นตัวเลขหลักทำให้ฉันสามารถบันทึกอีกหนึ่งไบต์ด้วยวิธีการต่อไปนี้:

^!(?!!{9})
1
r`!{0,9}
$.&
0\B

แต่รูปแบบอินพุตนี้ค่อนข้างยืดออกฉันคิดว่า


ดังนั้น Retina จะไม่อนุญาตให้ใช้ Integer หรือไม่สามารถจัดการเลขคณิตของเลขจำนวนเต็มได้
levanth

@levanth ไม่มีการคำนวณทางคณิตศาสตร์เลยใน Retina - ภาษาทั้งหมดนั้นใช้การประมวลผลสตริงผ่านการแสดงออกปกติดังนั้นเลขคณิตทั้งหมดจึงมักจะถูกนำมาใช้กับการเป็นตัวแทนที่ไม่เหมือนกัน Retina สามารถรับอินพุตจำนวนเต็มทศนิยมและแปลงเป็น unary ก่อน แต่มีค่าใช้จ่าย 6 ไบต์เพิ่มเติมและนโยบายของเราอนุญาตให้มีการป้อนข้อมูลแบบยูนารีเว้นแต่ความท้าทายจะระบุทศนิยม (หากคุณต้องการคำตอบทั้งหมดในการป้อนทศนิยมโปรดบอกในข้อกำหนดและฉันจะอัปเดตคำตอบของฉัน)
Martin Ender

ไม่ไม่เป็นไร ^^ ฉันแค่อยากรู้อยากเห็นเกี่ยวกับข้อมูลที่ไม่เกี่ยวกับ
ศาสนา


6

Java 7, 68 61 ไบต์

int f(int n){return n>9?-~(n%9)*(int)Math.pow(10,n/9)-1:n+9;}

ทำอย่างเดียวกันกับคำตอบอื่น ๆ ที่นี่หรือไม่ ต้องการแสดงวิธีการ Java โดยไม่ต้องใช้การจัดการสตริงและลูป

ขอบคุณ FryAmTheEggman ที่เตือนฉันว่าฉันโง่;)


อย่างน้อยคุณ outgolfed SQL?
Rɪᴋᴇʀ

Meh มีขนาดใหญ่เป็นสองเท่าของคำตอบ python / ruby ​​ที่นี่ดังนั้นฉันจึงไม่รู้สึกแย่กับ Java ตอนนี้ มันคงจะดีถ้าเอาชนะ C แม้ว่า: P
Geobits

: / โอ๊ะได้สิ่งนั้นมาจากบล็อกของฉัน ฉันต้องเป็นสนิมในสิ่งนี้
Geobits

@Geobits มันอาจชนะ C--
gcampbell

@Fry ลืมไปโดยสิ้นเชิงเกี่ยวกับเคล็ดลับที่ ขอบคุณที่ทำให้ฉันไปข้างหน้าของ C อย่างน้อย;)
Geobits

3

MATL , 10 9 ไบต์

`QtV!UsG-

ลองออนไลน์!

คำอธิบาย

`        % Do...while
  Q      %   Add 1. Takes input implicitly the first time
  t      %   Duplicate
  V!Us   %   To string, transpose, to number, sum. Gives sum of digits
  G-     %   Subtract input. If 0, the loop ends and the stack is implicitly displayed

1
การใช้V!U+1 อย่างชาญฉลาดจากฉัน นั่นควรจะอยู่ในรายการ MATLI ของเรา
Suever

@Suever ใช่ที่ใช้บ่อย ๆ
Luis Mendo


3

Python 3, 128 94 84 74 ไบต์

หากไม่มีเอาต์พุต, วิธีการโดยตรง, codegolfer เริ่มต้น;)

def r(n):
 m=n
 while 1:
  m+=1
  if sum(map(int,str(m)))==n:return(m)

1
สำหรับผู้เริ่มมีช่องว่างมากมายที่สามารถลบออกได้ ตัวอย่างก่อน / หลัง = + ()
Emigna

1
นอกจากนี้คุณสามารถแทนที่print(m)ด้วยreturn m(ไม่ได้บันทึกไบต์ใด ๆ แต่คุณไม่จำเป็นต้องพิมพ์ในฟังก์ชันเอง) คุณยังสามารถพิมพ์ฟังก์ชันส่งออกกลับด้วยprint(r(n))เพื่อทดสอบฟังก์ชั่นของคุณ
levanth

1
นอกจากนี้คุณยังสามารถลบบรรทัดใหม่ได้มากมาย m=n+1;f=1และif s==n:f=0
บลู

1
เมื่อแทนที่การพิมพ์ด้วยการส่งคืนคุณสามารถทำได้โดยตรงใน if-statement และลบ f รวมถึง else-statement
Emigna

2
คุณยังสามารถลบ f และใช้ในขณะที่ 1: และยังลบช่องว่างระหว่าง int (c) และสำหรับ
Emigna

2

ที่จริงแล้ว 17 ไบต์

╗1`;$♂≈Σ╜;)=)>*`╓

ลองออนไลน์!

คำอธิบาย:

╗1`;$♂≈Σ╜;)=)>*`╓
╗                  save input to reg0
 1`;$♂≈Σ╜;)=)>*`╓  first integer n (>= 0) where:
   ;$♂≈Σ╜;)=         the base-10 digital sum equals the input and
            )>*      is greater than the input

คำตอบนี้ดีมากเพราะมันมีสีสัน ( ;))
คดีกองทุนของโมนิกา

2

C 73 65 ไบต์

แมโครที่มีฟังก์ชันตัวช่วย

e(y){return y?10*e(y-1):1;}
#define F(n) n<9?n+9:(1+n%9)*e(n/9)-1

eฟังก์ชั่นเพียงคำนวณอำนาจของสิบและFแมโครใช้วิธีการแก้ปัญหาเช่นเดียวกับทับทิมนี้และงูหลามนี้คำตอบ น่าเศร้าที่มันยาวกว่าความยาวเดียวกันกับคำตอบทั้งคู่ แต่มันเป็นคำตอบ C แรก

(8 ไบต์บันทึกโดยกลอุบายของ Lynn ในการลบint)


คุณสามารถดร็อปทั้งสองได้intโดยประหยัดได้ 8 ไบต์
Lynn

2

Brachylog 8 ไบต์ (ไม่แข่งขัน)

<.=:ef+?

= ได้รับการแก้ไขหลังจากความท้าทายนี้ถูกโพสต์เพื่อให้สามารถทำงานบนโดเมนที่ไม่มีที่สิ้นสุดซึ่งในกรณีนี้

คำอธิบาย

<.       Output > Input
  =      Label the Output (i.e. unify it with an integer)
   :ef   Get the list of digits of the Output
      +? Input is the sum of all those digits

สิ่งนี้จะย้อนรอย=จนกว่าค่าของเอาต์พุตจะทำให้เป็นจริงทั้งหมด



1

Python 2, 39 ไบต์

lambda n:[n+9,(1+n%9)*10**(n/9)-1][n>9]

เลขจำนวนเต็มแท้

โปรแกรมเต็มพร้อมเอาต์พุต

f=lambda n:[n+9,(1+n%9)*10**(n/9)-1][n>9]

print(f(2))
print(f(8))
print(f(12))
print(f(16))
print(f(17))
print(f(18))
print(f(24))
print(f(32))

เอาท์พุท:

11
17
39
79
89
99
699
5999

ฉันชอบวิธีที่สูตรนี้หลีกเลี่ยงศูนย์นำ
Neil

@ ไม่มีอีกคนสามารถหลีกเลี่ยงได้โดยใช้eval
Blue

1

PowerShell v2 +, 62 ไบต์

param($n)for($a=$n+1;([char[]]"$a"-join'+'|iex)-ne$n;$a++){}$a

ใช้อินพุต$nจากนั้นเรียกใช้งานforลูป เรากำหนดค่าเริ่มต้นวนซ้ำโดยการตั้งค่าหมายเลขเป้าหมายของเรา$aให้ใหญ่กว่าหนึ่ง$n(เนื่องจากจะต้องมีขนาดใหญ่กว่าและสิ่งนี้ทำให้แน่ใจว่า1..9ทำงานได้อย่างถูกต้อง) $a++แต่ละวงที่เราเพิ่มขึ้น ไม่มีอะไรเกิดขึ้นในลูปที่เหมาะสม แต่เงื่อนไขเป็นที่ที่ตรรกะของโปรแกรมเกิดขึ้น เราใช้หมายเลขเป้าหมายเป็นสตริงชี้ไปที่มันเป็น char-array -joinใช้อาร์เรย์ด้วย+แล้วก็ไพพ์ไปที่iex(คล้ายกับeval) เราทดสอบว่ามันเท่ากับจำนวนอินพุตของเราหรือไม่และทำการวนซ้ำตามนั้น เมื่อเราออกจากลูปไปแล้วเราก็ไปถึงที่เป้าหมายของเราคือจำนวนผลรวมหลักเท่ากับจำนวนที่เราป้อนดังนั้น$aวางบนไพพ์ไลน์และเอาต์พุตจะเป็นนัย


สำหรับการอ้างอิงต่อไปนี้เป็น "วิธีสร้างสตริงที่มีจำนวน 9 วิธี" ที่เหมาะสมซึ่งบุคคลอื่นได้ทำไว้ที่ 67 ไบต์

param($n)(($n+9),(+(""+($n%9)+'9'*(($n/9)-replace'\..*'))))[$n-gt9]

หรือวิธีการ "เลขจำนวนเต็มบริสุทธิ์" ที่คนอื่น ๆ ทำได้ที่70 ไบต์

param($n)(($n+9),("(1+$n%9)*1e$(($n/9)-replace'\..*')-1"|iex))[$n-gt9]

ซึ่งทั้งสองอย่างนั้นสั้นกว่า แต่ทั้งคู่ก็น่าสนใจกว่า


คุณสามารถบันทึกได้ 3 ไบต์:param($n)for($a=$n+1;([char[]]"$a"-join'+'|iex)-$n){$a++}$a
mazzy

1

Pyke, 9 8 7 ไบต์, ไม่ใช่การแข่งขัน - ใช้เวอร์ชันที่ใหม่กว่า

.fhsq)h

ลองที่นี่!

.f      - first where true:
  h     - n+1
   sq    - digital_root(^) == input()
      h - that number +1

Tested again, your solution gives not the correct output for the inputs 1 to 8
levanth

I think I broke it... Works except for the number 1. Btw why does Missing arg to Equals, evaling input come up? I mean I give it an input number
levanth

@levanth That happens because by default the web interface has warnings turned on. I've just coded a way to turn that off (like 10 mins ago). As for why it didn't work for 1, I was checking to see if the number was bigger than 10 and if so continuing.
Blue

1

JavaScript (ES2015), 45 39 33 bytes

Saved another 6 bytes thanks to @Conor O'Brien and @Shaun H.
I think I'll leave it as is, because this version differs from @Neil's answer by using String.repeat().

v=>+(v>9?v%9+'9'.repeat(v/9):v+9)

Previous version (saved 6 bytes thanks to @Qwertiy):

f=v=>+(v/9>1?v%9+'9'.repeat(v/9|0):v+9)

First version:

f=v=>+(v/9>1?v%9+'9'.repeat(~~(v/9)):'1'+v-1)

1
~~(v/9) => v/9|0, '1'+v-1 => v+9
Qwertiy

@Qwertiy Thank you very much. I need to learn more about bitwise operators. About the second change, it looks like I overcomplicated the case for v <= 9. I'll think if I can return all numeric values, which could be another byte-saver (no .repeat() and wrapping return value in +()).
Leibrug

You don't need to name the function as per our rules
Conor O'Brien

1
v>9 is 2 bytes shorter, string.repeat will floor a decimal value no |0 needed
Shaun H

Also differs from my answer by not using ** of course.
Neil

1

Lua, 52 bytes

n=...+0
print(n>9 and(n%9)..string.rep(9,n/9)or n+9)

Meant to be saved in a file and run with the Lua interpreter, e.g. lua <file> <input number>

You can also try it here: https://repl.it/CXom/1

(On repl.it the input number is hard-coded for ease of testing)


What does the '...+0' do...? Does it cast the input to an integer?
Yytsi

1
Yep, to a number (Lua before 5.3 only used doubles, like JavaScript). Lua will automatically convert strings to numbers in expressions, but not comparisons. So in order for n>9 to work properly it needs to be coerced to a number first.
PiGuy

+1! I see. So ...+0>9 would work?
Yytsi

1
Yep! It would :)
PiGuy

1

Racket 70 characters, 71 bytes

Same algorithm as most of the others pretty much. Pretty sad about not having % for modulo, or ** for expt, or integer division by default, otherwise this could be a lot shorter and I could've outgolfed C and Java. Still love the language though

(λ(x)(if(> x 9)(-(*(+(modulo x 9)1)(expt 10(floor(/ x 9))))1)(+ x 9)))

1

Hexagony, 40 31 30 bytes

<_:->.(.+><.'!.\@"9!%>!/{.}|.?

Or, if you prefer your code to be a little less linear and a little more polygonal:

    < _ : -
   > . ( . +
  > < . ' ! .
 \ @ " 9 ! % >
  ! / { . } |
   . ? . . .
    . . . .

Try it online!

Thanks to @FryAmTheEggman for some ideas and inspiration :o)

Previous version: <.:->+_.!(..'!.\><9!%>@.{.}|.?"

Previouser version: <><.-_|@"'!{|(.9+!8=@>{/".'/:!?$.%\1$..\


1
This seems to work? Still looks golfable.
FryAmTheEggman

@FryAmTheEggman Nice work! 2 minutes after posting this I thought of a much better way to do, well, pretty much everything. Tunnel vision, probably? I'm working on a revised version.
Sok

Thanks :) Just an FYI people often chat about Hexagony in the esoteric programming languages room. Join in if you want :)
FryAmTheEggman

1
Managed to smoosh it in a bit more: hexagony.tryitonline.net/…
FryAmTheEggman

1

Perl 6,  38  29 bytes

{$_>9??(1+$_%9)*10**Int($_/9)-1!!$_+9}
{first *.comb.sum==$_,$_^..*}

( apparently the direct approach is shorter )

Explanation:

{
  first
    *.comb.sum == $_, # lambda that does the check
    $_ ^.. *          # Range.new: $_, Inf, :excludes-min
}

Test:

#! /usr/bin/env perl6

use v6.c;
use Test;

my @tests = (
   2 => 11,
   8 => 17,
   9 => 18,
  12 => 39,
  16 => 79,
  18 => 99,
  24 => 699,
  32 => 5999,
);

plan +@tests;

my &next-digital-sum = {first *.comb.sum==$_,$_^..*}

for @tests -> $_ ( :key($input), :value($expected) ) {
  is next-digital-sum($input), $expected, .gist;
}
1..8
ok 1 - 2 => 11
ok 2 - 8 => 17
ok 3 - 9 => 18
ok 4 - 12 => 39
ok 5 - 16 => 79
ok 6 - 18 => 99
ok 7 - 24 => 699
ok 8 - 32 => 5999

1

Java 10, 114 62 bytes

n->{var r="";for(int i=0;i++<n/9;r+=9);return(n>9?n%9:n+9)+r;}

Try it online.

EDIT: 130 73 bytes without leading zeros (Thanks to @levanth`):

n->{var r="";for(int i=0;i++<n/9;r+=9);return new Long((n>9?n%9:n+9)+r);}

Try it online.

Explanation:

n->                           // Method with integer parameter and long return-type
  var r="";                   //  Result-String, starting empty
  for(int i=0;i++<n/9;r+=9);  //  Append `n` integer-divided by 9 amount of 9's to `r`
  return new Long(            //  Cast String to number to remove any leading zeroes:
    (n>9?                     //   If the input `n` is 10 or larger
      n%9                     //    Use `n` modulo-9
     :                        //   Else (`n` is smaller than 10):
      n+9)                    //    Use `n+9`
    +r);}                     //   And append `r`

1
If anyone is interested: The fix would be seven bytes longer, replace String c(int n){return""+(n>9?(n%9)+s(n):n+9);} with int c(int n){return Integer.parseInt((n>9?(n%9)+s(n):n+9));}
levanth

@levanth I've edited it in. Btw, you forgot the ""+ in int c(int n){return Integer.parseInt(""+(n>9?(n%9)+s(n):n+9));}
Kevin Cruijssen

1

Ruby, 33 bytes

This is a int arithmetic version that just happens to be the same as xnor's python answer. It is an anonymous function that takes and returns an int.

->n{n<10?n+9:(1+n%9)*10**(n/9)-1}

I don't know ruby that much but is the -> at the start an anonymous function?
levanth

@levanth: yes. I will clarify above
MegaTom

Does not work for n=9
G B

@GB thank you for pointing that out. It is now fixed.
MegaTom

1

MathGolf, 8 7 bytes

Æ)_Σk=▼

Try it online!

Implicit input yay.

Explanation:

          Implicit input
 Æ     ▼  Do while false loop that pops the condition
  )       Increment top of stack
   _      Duplicate
    Σ     Get the digit sum
     k    Get input
      =   Is equal?
          Implicit output

I know this is an older answer, but you can solve it in 7 bytes now with implicit input (just skip the first k).
maxb

0

Ruby, 38 bytes

f=->n{n<11?n+9:"#{n<19?n-9:f.(n-9)}9"}

This answer returns a string or int depending on input size. It is a recursive solution that asks for a solution for 9 less then adds a "9" to the end.


Ruby, 39 bytes

f=->n{n<11?n+9:(n<19?n-9:f.(n-9))*10+9}

For one more byte, this answer always returns an int. same algorithm as above but with numbers.


0

C, 80 bytes

i;s;g(j){s=0;for(;j;j/=10)s+=j%10;return s;}f(n){i=n;while(n-g(i))i++;return i;}

Ungolfed try online

int g(int j)
{
    int s=0;
    for(;j;j/=10) s += j%10;
    return s;
}

int f(int n)
{
    int i=n;
    for(;n-g(i);i++);
    return i;
}


0

Oracle SQL 11.2, 165 bytes

SELECT l FROM(SELECT LEVEL l,TO_NUMBER(XMLQUERY(REGEXP_REPLACE(LEVEL,'(\d)','+\1')RETURNING CONTENT)) s FROM DUAL CONNECT BY 1=1)WHERE s=:1 AND l!=s AND rownum=1;

Un-golfed

SELECT l   
FROM   (
         SELECT LEVEL l, -- Number to evaluate
                XMLQUERY( 
                          REGEXP_REPLACE(LEVEL,'(\d)','+\1')  -- Add a + in front of each digit 
                          RETURNING CONTENT
                        ).GETNUMBERVAL()s                     -- Evaluate le expression generated by the added + 
                FROM DUAL 
                CONNECT BY 1=1 -- Run forever            
       )
WHERE s=:1      -- The sum must be equal to the input
  AND l!=s      -- The sum must not be the input 
  AND rownum=1  -- Keep only the first result

0

Python 3 55 Bytes

Takes two arguments that are the same

f=lambda a,b:a if sum(map(int,str(a)))==b else f(-~a,b)

i.e. to call it you would use f(x,x)



0

Powershell, 54 bytes

$args|%{(($_+9),+(''+$_%9+'9'*(($_-$_%9)/9)))[$_-gt9]}

Test script:

$f = {

$args|%{(($_+9),+(''+$_%9+'9'*(($_-$_%9)/9)))[$_-gt9]}

}

@(
    ,(  1,  10   )
    ,(  2 , 11   )
    ,(  8 , 17   )
    ,(  9 , 18   )
    ,( 10,  19   )
    ,( 11,  29   )
    ,( 12 , 39   )
    ,( 16 , 79   )
    ,( 18 , 99   )
    ,( 19 , 199  )
    ,( 24 , 699  )
    ,( 27 , 999  )
    ,( 32 , 5999 )
    ,( 52 , 799999 )
    ,( 128, 299999999999999 )
) | % {
    $a,$e = $_
    $r = &$f $a
    "$($r-eq$e): $r"
}

Output:

True: 1 : 10
True: 2 : 11
True: 8 : 17
True: 9 : 18
True: 10 : 19
True: 11 : 29
True: 12 : 39
True: 16 : 79
True: 18 : 99
True: 19 : 199
True: 24 : 699
True: 27 : 999
True: 32 : 5999
True: 52 : 799999
True: 128 : 299999999999999

Expalantion

  • if [$_-gt9] returns a first digit and a tail
    • a first digit is the difference between $_ and the sum of 9 ($_%9)
    • a tail is a few nines - '9'*(($_-$_%9)/9))
    • finally, converts a result string into a number to remove the leading 0
  • else returns ($_+9)
โดยการใช้ไซต์ของเรา หมายความว่าคุณได้อ่านและทำความเข้าใจนโยบายคุกกี้และนโยบายความเป็นส่วนตัวของเราแล้ว
Licensed under cc by-sa 3.0 with attribution required.